计算数组元素的总和,该元素可以为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 姐姐女儿结婚祝福语简短