我有一个总数组,其中包含其他值数组。 我希望在 forEach 和 reduce() 的帮助下添加嵌套值
// My main array
Total = [
[ 1, 0, 1, 0 ],
[ 0, 1, 0, 0 ],
[ 1, 0, 0, 1 ],
[ 0, 0, 1, 0 ],
[ 0, 1, 0, 0 ],
[ 1, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ] ]
// The code I have
Total.forEach(function(element) {
element.reduce(function(a,b) {
console.log(a+b)
}, 0)
})
// Output not as expected!
1
NaNNaNNaN0 NaNNaNNaN1 NaNNaNNaN0 NaNNaNNaN0 NaNNaNNaN1 []
我想要的是,例如,第一个 forEach 应该给出 1+0+1+0 = 2...
之和,依此类推
最佳答案
const Total = [
[1, 0, 1, 0],
[0, 1, 0, 0],
[1, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
];
let res = Total.map(x => x.reduce((res, curr) => res += curr, 0));
console.log(res);
关于javascript - 我希望在我的 javascript 数组上使用 reduce 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54056083/