计算数组元素的总和,该元素可以为null或未定义的JavaScript
假设我们有一个数组数组,每个数组包含一些数字以及一些未定义和null值。我们需要创建一个新数组,其中包含每个相应子数组元素的总和作为其元素。并且undefined和null值应计算为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 ]
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短