Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array iteration pitfall

Tags:

javascript

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

like image 451
Maizere Pathak.Nepal Avatar asked Jan 30 '26 21:01

Maizere Pathak.Nepal


1 Answers

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.

like image 178
999k Avatar answered Feb 01 '26 12:02

999k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!