首页 文章资讯内容详情

计算数组元素的总和,该元素可以为null或未定义的JavaScript

2026-06-04 1 花语

假设我们有一个数组数组,每个数组包含一些数字以及一些未定义和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 ]