javascript – for-in循环通过后续执行以相同的顺序迭代?
作者:互联网
众所周知,ECMA标准不保证特定的迭代次序,但我对迭代的实际顺序不感兴趣.我需要知道的是:如果在同一个会话期间多次执行,for for-in循环至少保证相同的迭代顺序,前提是在后续的for-in执行之间没有添加或删除迭代对象的属性?我猜可能没有理由不这样做,但我想找一些参考.
解决方法:
订单是任意的,您只能猜测它将始终以相同的顺序迭代.只是不要指望它总是一样的.
下面的引用是针对数组使用的for-in,同样适用于在对象属性上使用它.
Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order.
delete operator增加了一些额外的信息:
Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position–not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.
标签:javascript,ecmascript-5,for-in-loop 来源: https://codeday.me/bug/20190706/1399337.html