【发布时间】:2018-06-12 17:04:25
【问题描述】:
我有一个对象数组,我想对整个数组的对象中的所有“bps”值求和。
我的对象数组如下所示:
arr = [
{
date: "2017-06-14T14:00:00.000Z",
bps: 2
},
...
]
这是我的 reduce 函数:
arr.reduce((accum, currVal) => {
console.log(accum.bps);
console.log(currVal.bps);
console.log(accum.bps + currVal.bps);
return accum.bps + currVal.bps;
}, {
bps: 0
});
根据输出到控制台的内容,reduce 函数的第一次迭代后,返回值 0 并没有成为下一次迭代的累加器(它变成“未定义”)。为什么会出现这种情况?我的函数应该如何总结我数组中的所有“bps”值?
这就是控制台显示的内容
scripts.js:1024 0
scripts.js:1025 0
scripts.js:1026 0
scripts.js:1024 undefined
scripts.js:1025 0
scripts.js:1026 NaN
scripts.js:1024 undefined
scripts.js:1025 0
scripts.js:1026 NaN
scripts.js:1024 undefined
scripts.js:1025 0
scripts.js:1026 NaN
scripts.js:1024 undefined
scripts.js:1025 0
scripts.js:1026 NaN
scripts.js:1024 undefined
scripts.js:1025 0
scripts.js:1026 NaN
scripts.js:1024 undefined
scripts.js:1025 0
scripts.js:1026 NaN
scripts.js:1024 undefined
scripts.js:1025 0
scripts.js:1026 NaN
scripts.js:1024 undefined
scripts.js:1025 0
scripts.js:1026 NaN
scripts.js:1024 undefined
scripts.js:1025 0
scripts.js:1026 NaN
scripts.js:1024 undefined
scripts.js:1025 0
scripts.js:1026 NaN
scripts.js:1024 undefined
scripts.js:1025 1.95
scripts.js:1026 NaN
scripts.js:1024 undefined
scripts.js:1025 0
scripts.js:1026 NaN
scripts.js:1024 undefined
scripts.js:1025 0
scripts.js:1026 NaN
scripts.js:1031 NaN
【问题讨论】:
-
return accum.bps + currVal.bps返回一个数字 ... 它没有名为bps的属性 -
试试
arr.map(({bps}) => bps).reduce((a, b) => a + b); -
我现在看到了。感谢您的澄清 - 现在工作正常。
-
也可以使用 lodash
_.sumBy(arr, elem => elem.bps) -
感谢 fredrik.hjamer。实际上我今天开始使用 lodash,所以我会考虑摆脱我自己编写的函数 :)
标签: javascript arrays object functional-programming