javascript - 如何在 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:
- 给定上面的 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;
});
});
推荐阅读
- php - file_put_contents(): 读取 8192 字节失败,errno=21 是一个目录
- java - 为什么在此处使用 try catch 时出现错误“变量 num1 可能尚未初始化”?
- python - 如何在非路由脚本中使用 Flask-Mail 发送邮件
- c# - 使用 LINQ 对 c# 中的集合进行谓词过滤以及将结果与 List 进行比较的必要性
元素 - cypress - 如何查询通过
在测试 Web 组件时使用 Cypress - python - 如何在odoo中使用message_post_with_template函数发送邮件
- git - 没有冲突的 git 合并是否有可能破坏应用程序功能?
- javascript - Merge and sort multiple arrays using their ordering logic
- java - 覆盖 io.swagger.v3.oas.annotations.media.Schema 中的任何参数都会引发异常
- visual-studio - 我是否使用正确版本的 Visual Studio 进行应用程序开发?