【问题标题】:Chrome and probably Opera sort object properties automaticallyChrome 和可能的 Opera 会自动对对象属性进行排序
【发布时间】:2011-06-20 15:43:29
【问题描述】:

问题是:Chrome 会自动对对象的属性进行排序。

如果我有这样的对象:

var obj = {4: "first", 2: "second", 1: "third"};

那么当我下一步做时:

for(var i in obj) {
    console.debug(obj[i]);
}

我看到下一个:

third second first

但期望:

first second third

【问题讨论】:

标签: javascript


【解决方案1】:

永远不要依赖属性的顺序。它们是无序的,并且没有规范定义枚举属性的顺序。

Chrome orders properties with numeric keys numerically,而其他浏览器按插入顺序枚举它们。它取决于实现。

【讨论】:

  • there is no specification that defines in which order properties should be enumerated ..... 我有个主意。我们把它们放进去的顺序怎么样。
【解决方案2】:

您不应该期望for..in 循环中的键有任何特定顺序。来自the MDC docs

for...in 循环以任意顺序迭代对象的属性

如果要使用数字键排序,请使用数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多