我有一个对象数组。每个对象都具有一个“ amount”属性,该属性具有一个整数值,例如30000。我想使用reduce对其求和,但是它返回undefined。
如果我console.log()currentValue.amount返回值,没问题。我不太明白为什么在添加它们时会返回undefined。
let items = [
{ id: 0, name: "Food", amount: 30000 },
{ id: 1, name: "Insurance", amount: 25000 },
{ id: 2, name: "Rent", amount: 50000 }
]
let total = items.reduce((a, b) => {
console.log(b.amount); // 30000 (first loop)
a + b.amount; // undefined
}, 0);
console.log(total);
当然,我的预期结果是它将对值求和,最后将为变量“总计”分配每个对象的数量属性值的总和。
编辑:我忘了退货!
let items = [
{ id: 0, name: "Food", amount: 30000 },
{ id: 1, name: "Insurance", amount: 25000 },
{ id: 2, name: "Rent", amount: 50000 }
]
let total = items.reduce((a, b) => {
console.log(b.amount); // 30000 (first loop)
return a + b.amount; // 105000 OK
}, 0);
console.log(total);
答案 0 :(得分:0)
return
累加器。
let items = [{
id: 0,
name: "Food",
amount: 30000
},
{
id: 1,
name: "Insurance",
amount: 25000
},
{
id: 2,
name: "Rent",
amount: 50000
}
]
let total = items.reduce((a, b) => {
return a + b.amount;
}, 0);
console.log(total);
答案 1 :(得分:0)
使用return
,
Reduce函数必须返回一些东西,然后将其用作下一次迭代的函数的第一个参数。
let items = [
{ id: 0, name: "Food", amount: 30000 },
{ id: 1, name: "Insurance", amount: 25000 },
{ id: 2, name: "Rent", amount: 50000 }
]
let total = items.reduce((a, b) => {
return a + b.amount;
}, 0);
console.log(total);
答案 2 :(得分:0)
Array.prototype.reduce
通过从函数返回累加器来工作。您已经在第二行中忘记了return
关键字。
let items = [{id:0,name:"Food",amount:30000},{id:1,name:"Insurance",amount:25000},{id:2,name:"Rent",amount:50000}];
let total = items.reduce((a, b) => {
console.log(b.amount);
return a + b.amount;
}, 0);
console.log("Total:", total);
您还可以使用解构和箭头函数的隐式返回,如下所示:
let items = [{id:0,name:"Food",amount:30000},{id:1,name:"Insurance",amount:25000},{id:2,name:"Rent",amount:50000}];
let total = items.reduce((a, { amount: b }) => (console.log(b), a + b), 0);
console.log("Total:", total);