javascript - 虽然不能保证 for..in 循环中的元素顺序,但在实践中实现之间有什么偏差?

标签 javascript object for-loop enumeration for-in-loop

<分区>

我不记得在哪里,但我曾经看到它说 for..in 循环可以按照实现者喜欢的任何顺序遍历元素,包括向前、向后、随机或交替每次执行 for..in 循环时,在前进和后退之间。但在实践中,不知何故,我不认为后者是任何现有实现的真实情况。 (虽然,我们知道有一种浏览器喜欢把事情搞砸,所以你永远不能太确定,但我离题了。)

我的观点是,虽然在实践中 for..in 排序可能没有这么糟糕的偏差,但我想知道 ECMAScript 实现之间存在什么偏差(如果有的话)。我想现在主要有JScript、Chakra、Futhark、Carakan、JavascriptCore、SquirrelFish、V8、SpiderMonkey、TraceMonkey,仅供引用。

最佳答案

首先,这里是规范中关于枚举顺序的引用:

12.6.4 The for-in Statement

The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified. Properties of the object being enumerated may be deleted during enumeration. If a property that has not yet been visited during enumeration is deleted, then it will not be visited. 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.

我能马上想到的只有这些:

  • 较早的 (也许是当前的?) 版本的 IE 会将在枚举期间添加的新属性放在枚举的末尾,以便当前运行的 可以访问它们for-in

  • this bug report 中所述,V8 具有不同的枚举顺序,已关闭为 WorkingAsIntended

     var a = {"foo":"bar", "3": "3", "2":"2", "1":"1"};
    

    在 Firefox 和 V8 中的测试显示不同的顺序。

这不是一个列表。当然可能还有更多。我认为这是由@Pointy 的评论总结的。没有任何保证。即使您有一个对象以一致的方式可靠地枚举,这并不意味着它会在下一个版本升级时这样做。根据指定的方式使用工具,而不是仅仅看起来可以工作。

关于javascript - 虽然不能保证 for..in 循环中的元素顺序,但在实践中实现之间有什么偏差?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13440846/

相关文章:

c - 在达到数组长度后在我的循环中看到随机数?

javascript - JQuery Facebook 喜欢标签功能

javascript - 如何使用带有点的字符串作为属性层次结构来形成嵌套的 javascript 对象

javascript - 这是将多级深层对象数组转换为简洁对象数组的好方法吗?

java - java 中使用 hashmap 的替代 for 循环

batch-file - .bat 无意中删除子目录

javascript - 我可以使用 javascript 动态更改视频源吗?

javascript - javascript switch语句的问题

javascript - netty-socketio : client did not complete upgrade - closing transport

c++ - CIS115 GradeBook 应用程序不添加成绩