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
2 Answers
Reset to default 7Are 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])
.