javascript - for-in 循环在后续执行中是否以相同的顺序迭代?

标签 javascript ecmascript-5 for-in-loop

众所周知,ECMA 标准不保证特定的迭代顺序,但我对实际的迭代顺序不感兴趣。我需要知道的是:如果在同一 session 中执行多次,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 - for-in 循环在后续执行中是否以相同的顺序迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31949284/

相关文章:

javascript - 从键值对中的值获取键

javascript - 不使用 getPrototypeOf?

javascript - 仅限 ES5 : return value when match is found after iterating over various values in an array

javascript - 将函数添加到 javascript 的 Array 类中断循环

javascript - 为什么 for in 循环显示未定义的值

javascript - ASP.NET 中多个 JavaScript block 的性能影响?

php - jQuery jQGrid 在标题层单击时展开/折叠网格

javascript - 正则表达式 (HTML/Javascript) - 获取所有数字和句号

javascript - 澄清 Typescript 的目标和库设置的功能

javascript - 一个简单的 `continue` 语句是否可以替代将整个 for..in 循环体嵌套在 `if` 中?