从数组的数组中返回一个数组,其中每个项目都是 JavaScript 中相应子数组中所有项目的总和
javascriptweb developmentobject oriented programming更新于 2025/10/22 6:04:17
给定一个数组的数组,每个数组包含一组数字。我们必须编写一个函数来返回一个数组,其中每个项目都是相应子数组中所有项目的总和。
例如 −
如果输入数组是 −
const numbers = [ [1, 2, 3, 4], [5, 6, 7], [8, 9, 10, 11, 12] ];
那么我们的函数的输出应该是 −
const output = [10, 18, 50];
那么,让我们为这个函数编写代码 −
示例
const numbers = [
[1, 2, 3, 4],
[5, 6, 7],
[8, 9, 10, 11, 12]
];
const sum = arr => arr.reduce((acc, val) => acc+val);
const sumSubArray = arr => {
return arr.reduce((acc, val) => {
const s = sum(val);
acc.push(s);
return acc;
}, []);
};
console.log(sumSubArray(numbers));
输出
控制台中的输出将是 −
[ 10, 18, 50 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

