計算可能為空或未定義陣列中元素總和的 JavaScript


我們有一個數組的陣列,每個陣列都包含一些數字以及一些未定義和空值。我們需要建立一個新陣列,將每個相應子陣列的元素之和作為元素。將未定義和空值計算為 0。

以下是該問題的陣列示例:

const arr = [[
   12, 56, undefined, 5
], [
   undefined, 87, 2, null
], [
   3, 6, 32, 1
], [
   undefined, null
]];

該問題的完整程式碼如下:

示例

const arr = [[
   12, 56, undefined, 5
   ], [
      undefined, 87, 2, null
   ], [
      3, 6, 32, 1
   ], [
      undefined, null
]];
const newArr = [];
arr.forEach((sub, index) => {
   newArr[index] = sub.reduce((acc, val) => (acc || 0) + (val || 0));
});
console.log(newArr);

輸出

控制檯中的輸出如下所示:

[ 73, 89, 42, 0 ]

更新於: 19-8-2020

683 次瀏覽

開啟你的職業生涯

完成課程,獲取認證

開始
廣告
© . All rights reserved.