如何在forEach中嵌套一个forEach以获得JavaScript的sum



它给了我数组中的项目,但我不确定如何将这些项目加在一起

const numArrays = [
[100, 5, 23],
[15, 21, 72, 9],
[45, 66],
[7, 81, 90]
];
total = [];
numArrays.forEach(function(n){
total += n;
});
console.log('Exercise 15 Result: ', total);

/*练习15:

  • 给定上面的numArrays数组,使用嵌套的forEach方法将numArrays中包含的所有数字相加,并分配给一个名为total的变量
  • 提示:一定要在迭代之前声明并初始化总变量。*/
const numArrays = [
[100, 5, 23],
[15, 21, 72, 9],
[45, 66],
[7, 81, 90]
];
let total = 0;
numArrays.forEach((parent) => {
parent.forEach((child) => {
total += child;
});
});

我可以通过嵌套的forEach方法将numArrays中包含的所有数字相加。它有效。

const numArrays = [
[100, 5, 23],
[15, 21, 72, 9],
[45, 66],
[7, 81, 90]
];
total = 0;
numArrays.forEach(function(n){
n.forEach(function(value) {
total += value;
})
});
console.log('Exercise 15 Result: ', total);

这就是reduce方法的作用。cur是迭代的当前值-100,5,23。Accum是上一次盘点。我们从0开始。每次在函数中返回值时,accum都会更新。

numArrays.reduce((accum1, cur1) => (
accum1 + cur1.reduce((accum2, cur2) => (
accum2 + cur2
), 0)
), 0)

您可以使用reduce

numArrays.reduce((acc, arr) => acc + arr.reduce((accumulator, currentValue) => accumulator + currentValue), 0);

最新更新