我有一个总数组,里面有其他值数组。 我希望借助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...
的总和,依此类推
答案 0 :(得分:1)
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);
答案 1 :(得分:1)
您可以尝试此代码
var 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 ] ];
function myFunction(){
for(let i=0 ;i<Total.length;i++){
console.log(Total[i].reduce(getSum));
}
}
function getSum(total, num) {
return total + num;
}
myFunction();
希望这会有所帮助