我正在做这段代码:
Class Cash
{
constructor(v, q)
{
this.value = v;
this.quantity = q;
}
var money = [];
money.push( new Cash(50, 4);
money.push( new Cash(20, 4);
money.push( new Cash(10, 2);我需要这样做:
(money[0].value * money[0].quantity) + (money[1].value * money[1].quantity) + (money[n].value * money[n].quantity)3个数组的预期结果是300 (50 * 4) + (20 * 4) + (10 * 2)
这个想法是,无论我把多少东西放入货币中,它都会继续做push乘积
我试过了,但不起作用:
for (i = 0; i > money.length; i++)
{
(money[i].value * money[i].quantity) + (money[i++].value * money[i++].quantity)
}发布于 2021-06-09 04:41:00
简单的for循环
var total = 0;
for( var i =0; i< money.length; i++) {
total += money[i].value * money[i].quantity;
}
console.log(total);或者使用reduce
const total = money.reduce(function (total, item) {
return total + item.value * item.quantity;
}, 0);
console.log(total);发布于 2021-06-09 04:41:39
您可以按如下方式使用函数Array.prototype.reduce:
class Cash {
constructor(v, q) {
this.value = v;
this.quantity = q;
}
}
const money = [new Cash(50, 4), new Cash(20, 4), new Cash(10, 2)],
result = money.reduce((a, m) => a + (m.value * m.quantity), 0);
console.log(result);
发布于 2021-06-09 04:46:11
请参阅下面的注释以获取修复。
class Cash { /* class, not Class */
constructor(v, q) {
this.value = v;
this.quantity = q;
}
} /* close your class declaration */
const money = [];
money.push(new Cash(50, 4)); /* close your parenthesis */
money.push(new Cash(20, 4)); /* close your parenthesis */
money.push(new Cash(10, 2)); /* close your parenthesis */
let sum = 0; /* initialize a sum variable with value 0 to retain results */
for (m of money) { /* or for (let i = 0; i < money.length; i++)
/* Assign result of sum/product to something
* More accurately add it to sum */
sum += m.value * m.quantity;
}
console.log(sum);
https://stackoverflow.com/questions/67894261
复制相似问题