我在嵌套for循环中使用splice
,我遇到了一个我无法理解的行为。javascript拼接跳过元素 - 为什么这个行为
var a = [0, 1, 2, 3, 4];
for (b in a) {
console.log(a);
for (c in a) {
console.log(c + '==' + a[c]);
if (c === "1")
a.splice(c, 1);
}
}
console.log(a);
它的输出是奇怪
[0, 1, 2, 3, 4]
"0==0"
"1==1"
"2==3" // why is index 2 referring to value 3 , whereas it should refer to 2
"3==4"
[0, 2, 3, 4]
"0==0"
"1==2"
"2==4" // index 2 referring to value 4 , whereas it should refer to 3
[0, 3, 4]
"0==0"
"1==3"
[0, 4]
我剪接指标1,它是跳过下一个元素。
为什么这种行为......
这里结账:http://jsbin.com/isahoj/3/edit
编辑:
行,我明白,它拼接后转移的索引,但我打电话做的console.log后拼接() ...那么它是如何拼接的?
在JavaScript中使用'for ... in'循环与数组不是一个好主意(通常)。使用索引变量。 – Pointy 2013-02-16 14:28:25
我已更新[我的答案](http://stackoverflow.com/a/14911384/157247)以回应您的修改。 – 2013-02-16 18:09:18