【发布时间】:2019-04-12 02:31:00
【问题描述】:
我尝试循环二维数组,但 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 次,第一个顶部代码是每个长度在数组中是不同的 和最后的代码是一样的,
【问题讨论】:
-
为什么要再次解构和构建数组?
-
我也从 answrr @JonasWilms 在 stackoverflow 上看到了这种方式
-
解构比循环更好吗?
标签: javascript arrays for-loop multidimensional-array iterator