gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 11:44:55 25 4
gpt4 key购买 nike

我尝试循环二维数组,但 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com