javascript - 为什么我的变量在循环时不可迭代

标签 javascript arrays for-loop multidimensional-array iterator

我尝试循环二维数组,但 I 变量未定义或不可迭代,为什么? 谁能告诉我吗??

function sum (arr) {
  var total = 0
  for(let [a1,a2,a3] of arr){
    for(let i of [a1,a2,a3]){
      for(let j of i){
        total += j
      }
    }
    if(typeof a2 == "undefined" && typeof a3 == "undefined"){
      a2 = [0]
      a3 = [0]
    }
  }     
};


console.log(sum([
  [
    [10, 10],
    [15],
    [1, 1]
  ],
  [
    [2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
    [4],
    [9, 11]
  ],
  [
    [3, 5, 1],
    [1, 5, 3],
    [1]
  ],
  [
    [90]
  ]
]));

但是当我对另一个二维数组求和时,它会起作用,如下所示:

function sum (arr) {
  var total = 0
  for(let [a1,a2,a3] of arr){
    for(let i of [a1,a2,a3]){
      for(let j of i){
        total += j
      }
    }
  }
  return total
}  


console.log(sum([
  [
    [4, 5, 6],
    [9, 1, 2, 10],
    [9, 4, 3]
  ],
  [
    [4, 14, 31],
    [9, 10, 18, 12, 20],
    [1, 4, 90]
  ],
  [
    [2, 5, 10],
    [3, 4, 5],
    [2, 4, 5, 10]
  ]
]));

我尝试为这个二维数组循环3次,第一个顶部代码是每个长度在数组中不同 最后的代码是相同的,

最佳答案

原因

 let [a1,a2,a3] of [ [90] ])

将导致a2a3未定义,因此在下面的行中是:

 for(const i of [90, undefined, undefined])

在第二个索引处它是这样的:

 for(let j of undefined)

这不起作用。

关于javascript - 为什么我的变量在循环时不可迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53210167/

相关文章:

javascript - 在 Node 中遍历 page.evaluate

javascript - 我的 href 链接按钮无法联机使用

javascript - 有条件地将 prop 传递给组件

javascript - 选择缺少 type 属性的 HTML <input> 元素 - jQuery

javascript - 如何在数组末尾留下逗号空间?

php - explode函数的反义词是什么?

php - for循环只返回最后的结果 - php

javascript - Scriptaculous Droppables onDrop 回调,如何引用每个元素?

php - 一定要有唯一的数组条目

java - Java 中增强的 for 循环和迭代器