最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Chrome and probably Opera sort object properties automatically - Stack Overflow

programmeradmin2浏览0评论

Problem is: Chrome automatically sorts properties of object.

If I have an object like:

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

then when I do next:

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

I see next:

third second first

but expect:

first second third

Problem is: Chrome automatically sorts properties of object.

If I have an object like:

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

then when I do next:

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

I see next:

third second first

but expect:

first second third

Share Improve this question edited Nov 13, 2011 at 12:42 Luc125 5,85735 silver badges35 bronze badges asked Feb 3, 2011 at 12:45 settysetty 2152 silver badges14 bronze badges 1
  • possible duplicate of [Sorting javascript by property value ](stackoverflow.com/questions/1069666/…) – viam0Zah Commented Feb 3, 2011 at 12:50
Add a comment  | 

2 Answers 2

Reset to default 18

Never rely on the order of properties. They are unordered and there is no specification that defines in which order properties should be enumerated.

Chrome orders properties with numeric keys numerically, whereas other browsers enumerate them in insertion order. It is implementation dependent.

You should not expect any particular order for keys in for..in loops. From the MDC docs:

A for...in loop iterates over the properties of an object in an arbitrary order

If you want ordering using numerical keys, use an array.

发布评论

评论列表(0)

  1. 暂无评论