[英]Please I wish to use the reduce method on my javascript array of arrays
I have a total array that has other arrays of values inside. 我有一个总数组,里面有其他值数组。 I wish to add the nested values with the help of forEach and reduce()
我希望在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 []
What I want is for example, The first forEach should give the sum of 1+0+1+0 = 2...
And so on 例如,我想要的是,第一个forEach应该给出
1+0+1+0 = 2...
的总和。
you can try this code 你可以试试这个代码
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();
Hope this helps 希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.