首页 > 解决方案 > 请我希望在我的 javascript 数组上使用 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 []

例如,我想要的是,第一个 forEach 应该给出1+0+1+0 = 2... 等的总和

标签: javascriptarrays

解决方案


你可以试试这段代码

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();

希望这可以帮助


推荐阅读