我正在尝试理解reduce的工作原理。
var expense = [
{
item: "Bed",
cost: 1499,
date: "02-23-2018"
},
{
item: "Phone",
cost: 2499,
date: "02-23-2018"
},
{
item: "Book",
cost: 400,
date: "02-23-2018"
},
{
item: "Mattress",
cost: 700,
date: "02-23-2018"
},
{
item: "Food",
cost: 300,
date: "02-23-2018"
}
];
var totalExpense = expense.reduce(function (a, b) {
console.log(a.cost, b.cost);
return a.cost + b.cost;
});
console.log(totalExpense);
这将使得totalExpense的值为NaN
输出结果:
1499 2499
undefined 400
undefined 700
undefined 300
NaN
当我使用一个简单的支出数组进行相同的操作时,它能够正常工作。
undefined
。 如果使用undefined
的.cost
会导致崩溃。实际上我错了,运行代码时会立即出现TypeError: Reduce of empty array with no initial value
。 - Viktor