簡體   English   中英

請我希望在我的JavaScript數組數組上使用reduce方法

[英]Please I wish to use the reduce method on my javascript array of arrays

我有一個總數組,里面有其他值數組。 我希望在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...的總和。

使用嵌套有reduce地圖嘗試此方法:

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

你可以試試這個代碼

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

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM