我有一个对象数组,我想在我的对象中为整个数组求和所有“bps”值。
我的对象数组如下所示:
arr = [
{
date: "2017-06-14T14:00:00.000Z",
bps: 2
},
...
]
这是我的缩减功能:
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
答案 0 :(得分:3)
由于您的reduce只是将所有.bps
值一起添加,您可以简单地将所有数组项映射到数字数组,然后将它们一起添加
arr.map(({bps}) => bps)
.reduce((a, b) => a + b);
甚至
arr.reduce((accum, {bps}) => accum + bps, 0);
答案 1 :(得分:1)
您应该返回一个具有<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input value="1000"/>
键的对象,而不是纯粹的总和。
即。 bps
代替return { bps: accum.bps + currVal.bps };
return accum.bps + currVal.bps;
<击> 或者(这实际上会更快,特别是对于长数组,因为它不会创建不必要的对象,只会创建结果对象。)
arr
.reduce((accum, currVal) => {
console.log(accum.bps);
console.log(currVal.bps);
console.log(accum.bps + currVal.bps);
return { bps: accum.bps + currVal.bps };
}, {
bps: 0
})
.bps;
击> <击> 撞击>
答案 2 :(得分:0)
这很有效。 accum是一个数字,所以不要使用accum.bps。此外,初始值是一个数字,所以不要使用{bps:0},只需使用0。
arr = [{
date: "2017-06-14T14:00:00.000Z",
bps: 2
}, {
date: "2017-05-14T14:00:00.000Z",
bps: 9
}, {
date: "2017-08-14T14:00:00.000Z",
bps: 4
}]
// Here is my reduce function:
arr.reduce((accum, currVal) => {
console.log("accum-" + accum);
console.log("currVal.bps-" + currVal.bps);
console.log("return value-" + (accum + currVal.bps));
return accum + currVal.bps;
}, 0);
这是输出:
accum-0
currVal.bps-2
return value-2
accum-2
currVal.bps-9
return value-11
accum-11
currVal.bps-4
return value-15