What is going wrong in this bit of code that i always get the unexpected output?
var foo = [3,4,5];
for ( var i in foo ) {
if ( i == 1 ) {
foo.unshift(6,6);
}
document.write('item: '+foo[i]+"<br>")
}
output:
item: 3
item: 6
item: 3
Can i get an appropriate reason for this?thank u
The output i got in IE8 is this
item: 3
item: 6
item: 3
item: 4
item: 5
Which is correct. If you want Fully updated value after the unshift use another loop
var foo = [3,4,5];
for ( var i in foo ) {
if ( i == 1 ) {
foo.unshift(6,6);
}
}
for ( var i in foo )
document.write('item: '+foo[i]+"<br>")
Which will give
item: 6
item: 6
item: 3
item: 5
item: 4
In your code when you call document.write('item: '+foo[i]+"<br>") with i = 0 Your foo[0] is 3
For i=1 after unshift foo == [6,6,3,4,5] ie foo[1] is 6.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With