这段代码出了什么问题,我总是得到意外的输出?
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
我能得到一个适当的理由吗?谢谢你
这段代码出了什么问题,我总是得到意外的输出?
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
我能得到一个适当的理由吗?谢谢你
我得到的输出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 = 0
Your foo[0]
is 3
For调用时。i=1
unshift
foo == [6,6,3,4,5]
foo[1]
6
for...in
的摘要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
弹出一次