I was working with splice
within a nested for loop and I came across a behaviour I could not understand.
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);
Its output is strange
[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]
I am splicing index 1 and it is skipping the next element .
Why this Behaviour ...
Here checkout : http://jsbin.com/isahoj/3/edit
EDIT:
ok , I understand that it shifts the index after splicing , but I am calling splice after doing console.log()... so how is it spliced earlier?