3

这段代码出了什么问题,我总是得到意外的输出?

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

我能得到一个适当的理由吗?谢谢你

4

2 回答 2

1

我得到的输出IE8是这个

item: 3
item: 6
item: 3
item: 4
item: 5

哪个是对的。如果您想在unshift使用另一个循环后完全更新值

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>")

哪个会给

item: 6
item: 6
item: 3
item: 5
item: 4

在您的代码中,当您在ie is之后document.write('item: '+foo[i]+"<br>")使用i = 0Your foo[0]is 3 For调用时。i=1unshift foo == [6,6,3,4,5]foo[1]6

于 2013-04-12T05:35:16.747 回答
0

for..in should not be used to iterate over an Array where index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties.
There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.forEach or the non-standard for...of loop) when iterating over arrays where the order of access is important.

If new properties are added to the object being enumerated during enumeration, the newly added properties are not guaranteed to be visited in the active enumeration. A property name must not be visited more than once in any enumeration.

让我们用例子来谈谈,如果我们正在使用一个库,它使用。

Array.prototype.maxLimit = 100000;

此属性遍历for .. in循环。

另一个版本的代码来解释for .. in循环

var foo = [3,4,5];

for ( var i in ( alert( JSON.stringify(foo)) || foo ) ) {

    if ( i == 1 ) {
       foo.unshift(6,6);
    }
    console.log('item: '+foo[i] , i , foo.length );    
}

alert弹出一次

于 2013-04-12T06:07:59.697 回答