Javascript-For循环键仅在第一次迭代中未定义? [英] Javascript - For Loop key undefined ONLY for 1st iteration?

查看:60
本文介绍了Javascript-For循环键仅在第一次迭代中未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在array [j]的第一次迭代中总是打印UNDEFINED?

Why does this always print UNDEFINED for the first iteration of array[j]??

var array = [1,2,3,4,5]
for (i in array) {

    console.log("array[i]:" +array[i]);

    for (j=i+1; j<array.length-1;j++) {

        console.log("array[j]:"+ array[j]);
    }
}

推荐答案

这是因为i包含字符串值,而不是数字.

That's because i contains a string value, not a number.

j设置为i+1会使它成为"0"+1,而不是0+1,因此是"01".由于array中没有键"01"的项目,因此您会返回undefined.

Setting j to i+1 makes it "0"+1, not 0+1, so that is "01". As there is no item in array with the key "01" you get undefined back.

执行j++时,它将把"01"转换为数字1并增加它,以便循环将按预期运行到最后.

When j++ is executed, it will convert the "01" into the number 1 and increase it, so that loop will run as expected to the end.

对于外循环中的下一个迭代,您得到j = "11",并且将其与数组的长度进行比较时,它将跳过内循环.对于外循环中的其余迭代,由于j将在数组外部开始,因此将跳过内循环.

For the next iteration in the outer loop, you get j = "11", and when that is compared to the length of the array it will skip the inner loop. For the rest of the iterations in the outer loop, the inner loop will be skipped as j will start outside of the array.

这篇关于Javascript-For循环键仅在第一次迭代中未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆