计算数组中可以为 null 或 undefined 的元素之和 JavaScript
javascriptweb developmentobject oriented programming更新于 2025/9/26 3:24:17
假设我们有一个数组数组,每个数组包含一些数字以及一些 undefined 和 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 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

