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

Are there any major browsers that do not preserve insertion order in a JavaScript Object? - Stack Overflow

programmeradmin2浏览0评论

Can I depend on the following code alerting b before a?

var x = {}
x['b'] = 1
x['a'] = 0
for(var i in x) {
    alert(i)
}

Can I depend on the following code alerting b before a?

var x = {}
x['b'] = 1
x['a'] = 0
for(var i in x) {
    alert(i)
}
Share Improve this question edited May 26, 2011 at 14:07 700 Software asked May 26, 2011 at 13:58 700 Software700 Software 88k88 gold badges242 silver badges347 bronze badges 1
  • 1 I don't know, but my gut says you shouldn't have to. If you need to depend on the order, use numeric indexes. – Pekka Commented May 26, 2011 at 13:59
Add a ment  | 

2 Answers 2

Reset to default 7

Are there any major browsers that do not preserve insertion order in a JavaScript Object?

At least one major browser did until recently (I think the V8 engine didn't preserve order).

Can I depend on the following code alerting b before a?

No. The spec says that there is no order.

For the V8 JavaScript engine used in Google Chrome, a similar discussion took place:

http://code.google./p/v8/issues/detail?id=164

It's better to not rely on undocumented features. And it you're using numbers as keys, it certainly goes wrong.

For example this breaks in some browsers:

var x = {}
x['b'] = 1
x['2'] = 20
x['a'] = 0
x['1'] = 10
for(var i in x) {
    alert(x[i])
}

BTW it's alert(x[i]).

发布评论

评论列表(0)

  1. 暂无评论