JavaScript 中二维数组元素的列和
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/30 23:08:17
我们有一个数组数组,需要编写一个函数,该函数接受此数组并返回一个新数组,该新数组表示原始数组相应元素的总和。
如果原始数组是 −
[ [43, 2, 21], [1, 2, 4, 54], [5, 84, 2], [11, 5, 3, 1] ]
输出
那么输出应该是 −
[60, 93, 30, 55]
让我们编写函数addArray() −
示例
该函数的完整代码如下 −
const arr = [
[43, 2, 21],
[1, 2, 4, 54],
[5, 84, 2],
[11, 5, 3, 1]
];
const sumArray = (array) => {
const newArray = [];
array.forEach(sub => {
sub.forEach((num, index) => {
if(newArray[index]){
newArray[index] += num;
}else{
newArray[index] = num;
}
});
});
return newArray;
}
console.log(sumArray(arr));
在这里,我们遍历原始数组的每个元素,然后遍历每个数字,检查该索引的总和是否已经存在,我们只需将相应的数字添加到它,否则我们将相应的数字设置为等于它。
输出
控制台中的输出将是 −
[ 60, 93, 30, 55 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

