在产生多个数组的循环中,如何 return 一个包含所有数组之和的数组

In a loop that results in several arrays, how to return an array with the sum of all of them

我有一个字符串数组,经过一番努力,我成功地把它变成了几个带有循环的数组。所以现在,循环给了我类似的东西:

[4,5,6,7,8]
[4,5,6,7,8],[1,2,3,4,5]
[4,5,6,7,8],[1,2,3,4,5],[22,33,44,55,66]

如果我将 return 放在代码的较低位置,我会得到: [[4,5,6,7,8],[1,2,3,4,5],[22,33,44,55,66]]

我需要的是这些数组的垂直和,所以在这种情况下是: [27,40,53,66,80]

到目前为止,我使用的是“.push”。另外,console.log 给了我这个答案,但 return 结果是 'undefined'。欢迎对这两件事提供任何帮助!

----更新----

正如这里有人建议的那样,我尝试了这个,但它并不完全有效:

array=[ [ 1, 2, 4 ], [ 4, 1, 5 ], [ 0, 5, 2 ] ];
let adding=0
const result=[]
for (let i = 0; i < array[0].length; ++i) {
    for (let j = 0; j < array.length; ++j) {
            adding += array[j][i];
            }
            result.push(adding);}
console.log(result)
    ```

The ouput is: [ 5, 13, 24 ] instead of [5,8,11]

1) 您可以使用 map and reduce

轻松获得结果

const arr = [
  [4, 5, 6, 7, 8],
  [1, 2, 3, 4, 5],
  [22, 33, 44, 55, 66],
];

const result = arr[0].map((_, i) => arr.reduce((acc, curr) => acc + curr[i], 0));
console.log(result)

2) 使用简单的 for 循环

const arr = [
  [4, 5, 6, 7, 8],
  [1, 2, 3, 4, 5],
  [22, 33, 44, 55, 66],
];

const result = [];

for (let i = 0; i < arr[0].length; ++i) {
  let sum = 0;
  for (let j = 0; j < arr.length; ++j) {
    sum += arr[j][i];
  }
  result.push(sum);
}

console.log(result);