【问题标题】:To find the sum of elements of a nested array using a for loop with javascript [duplicate]使用带有javascript的for循环查找嵌套数组的元素总和[重复]
【发布时间】:2021-08-20 10:53:48
【问题描述】:

我有一个嵌套循环:

const arrays = [
  [4, 32, 8],
  [64, 8, 32],
  [8, 32, 16],
  [2, 8, 4]
] 

我想使用 For 循环找到所有元素的总和,并在控制台中显示结果。我该怎么做?

【问题讨论】:

  • 你应该研究一下。有很多关于这个主题的问答。
  • 嗨!请使用tour(您将获得徽章!)并通读help center,尤其是How do I ask a good question? 您最好的选择是进行研究,search 以获取有关 SO 的相关主题,然后试一试. 如果您在进行更多研究和搜索后遇到困难并且无法摆脱困境,请发布您的尝试minimal reproducible example,并具体说明您遇到的问题。人们会很乐意提供帮助。 (请注意我的反对意见。)

标签: javascript arrays for-loop


【解决方案1】:

试试这个

const arrays = [
  [4, 32, 8],
  [64, 8, 32],
  [8, 32, 16],
  [2, 8, 4]
] 

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

console.log(sum);

【讨论】:

猜你喜欢
  • 2020-11-15
  • 2019-03-18
  • 1970-01-01
  • 2021-12-17
  • 2020-02-22
  • 2021-10-14
  • 1970-01-01
  • 2020-09-13
  • 2015-10-07
相关资源
最近更新 更多