計算可能為空或未定義陣列中元素總和的 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 ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP