【问题标题】:How to nest a forEach in a forEach to get sum for JavaScript如何在 forEach 中嵌套 forEach 以获取 JavaScript 的总和
【发布时间】:2021-02-02 20:09:05
【问题描述】:

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

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 的变量。
  • 提示:请务必在迭代前声明并初始化总变量。 */

【问题讨论】:

  • 代码是用什么语言编写的?请edit您的问题将其添加为标签。
  • 谢谢,我确实更新了我的标签和语言

标签: javascript arrays multidimensional-array foreach


【解决方案1】:
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;
    });
});

【讨论】:

  • 谢谢。我知道它必须嵌套,但不知道该怎么做!
【解决方案2】:

我可以通过嵌套的 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);

【讨论】:

    【解决方案3】:

    这就是 reduce 方法的用途。 cur 是迭代的当前值 - 100、5、23。Accum 是之前的计数。我们从 0 开始。 每次你在函数中返回一个值 - accum 都会更新。

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

    【讨论】:

      【解决方案4】:

      你可以使用reduce

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

      【讨论】:

        猜你喜欢
        • 2018-02-17
        • 1970-01-01
        • 2018-07-01
        • 1970-01-01
        • 2019-09-13
        • 1970-01-01
        • 2022-11-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多