这段代码出了什么问题,我总是得到意想不到的输出?
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
我可以得到合适的理由吗?谢谢你
答案 0 :(得分: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
当您使用document.write('item: '+foo[i]+"<br>")
i = 0
致foo[0]
时,在您的代码中3
为i=1
对于unshift
foo == [6,6,3,4,5]
之后的foo[1]
,6
为{{1}}。
答案 1 :(得分:0)
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
仅{{1}}弹出一次