计算可能为空或未定义阵列中元素总和的 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