javascript - 使用 underscore.js 和 reduce 对数组内的对象求和

标签 javascript underscore.js

我正在尝试使用 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/

相关文章:

javascript - 如何计算对象数组中每个键的出现次数?

javascript - 存储与 jquery 一起使用的数据的最佳方式是什么?

javascript - Switch 语句不更新 Document.getElementById()

javascript - 合并一组相似对象的值

javascript - 过滤具有重复标题和唯一描述的对象数组?

JavaScript 绑定(bind)语法

javascript - 如何开 Jest 模拟另一个 react 组件中的函数?

javascript - *无需*浏览器,仅使用 JavaScript 解释器即可创建 webRTC 对等体

javascript - 下划线 _.intersection() - 怎么做?

javascript - 在下划线中使用去抖功能