我正在尝试使用 underscore.js 及其 reduce 方法对内部对象和数组的值求和。但看起来我做错了什么。我的问题在哪里?
let list = [{ title: 'one', time: 75 },
{ title: 'two', time: 200 },
{ title: 'three', time: 500 }]
let sum = _.reduce(list, (f, s) => {
console.log(f.time); // this logs 75
f.time + s.time
})
console.log(sum); // Cannot read property 'time' of undefined
最佳答案
使用原生的 reduce
因为 list
已经是一个数组。
reduce
回调应该返回一些东西,并有一个初始值。
试试这个:
let list = [{ title: 'one', time: 75 },
{ title: 'two', time: 200 },
{ title: 'three', time: 500 }];
let sum = list.reduce((s, f) => {
return s + f.time; // return the sum of the accumulator and the current time, as the the new accumulator
}, 0); // initial value of 0
console.log(sum);
注意:如果我们省略 block 并使用箭头函数的隐式返回,则可以进一步缩短reduce
调用:
let sum = list.reduce((s, f) => s + f.time, 0);
关于javascript - 使用 underscore.js 和 reduce 对数组内的对象求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42069355/