2

Possible Duplicate:
Elements order - for (... in ...) loop in javascript

Assume you have code like this:

var a = {}
a.a = 1;
a.c = 2;
a.b = 3;

for (var i in a) {
    console.log(a[i]);
}

Are 1, 2, and 3 guaranteed to be printed in that order? I've tested and this has been the case so far, but I don't know if it'll always be true. Is there any browser which does not do this? There's nothing weird going on, like deleting things, prototype inheritance, etc. Just adding properties to an object.

1

2 Answers 2

3

All current browsers with the exception of Chrome will loop over the properties of an object in the same order as they were defined.

Here is the chrome bug report: http://code.google.com/p/chromium/issues/detail?id=883. It is currently marked as WontFix.

Sign up to request clarification or add additional context in comments.

5 Comments

From ecma-international.org/publications/files/ECMA-ST/Ecma-357.pdf: The order in which item is bound to members of collection is implementation dependent. I guess it would be more appropriate to use an array when order is significant.
@harto: nice link. That quote is actually referring to the newer "for each" loop construct, although there is a similar doc somewhere that says the same thing for "for in". Either way it's the reason V8 won't be "fixing" this anytime soon.
@harto: in ecmascript 5 the order is defined as being the order of insertion
Google's attitude on this is uncharacteristically obstuctive - see bug comments 16 and 17 :) Hopefully ecma5 motivates them to "fix" this sooner rather than later.
ollieJ, the Ecmascript 5 standard I downloaded and skimmed seemed to say the opposite: that "The mechanics and order of enumerating the properties... is not specified."
1

In my current version of Chrome (2.0.172.28) John Resig's test case passes, so maybe it is fixed in Chrome now?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.