首页 > 解决方案 > 如何在 forEach 中嵌套 forEach 以获取 JavaScript 的总和

问题描述

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

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:

标签: javascriptarraysmultidimensional-arrayforeach

解决方案


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;
    });
});

推荐阅读