我有一个对象数组,我想对整个数组的对象中的所有“ 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
由于reduce只是将所有.bps
值加在一起,因此您可以简单地将所有数组项映射到一个数字数组,然后将它们加在一起
arr.map(({bps}) => bps)
.reduce((a, b) => a + b);
甚至
arr.reduce((accum, {bps}) => accum + bps, 0);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句