views:

186

answers:

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.

+3  A: 

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.

Crescent Fresh
From http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-357.pdf: The order in which item is bound to members of collectionis implementation dependent. I guess it would be more appropriate to use an array when order is significant.
harto
@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.
Crescent Fresh
@harto: in ecmascript 5 the order is defined as being the order of insertion
olliej
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.
annakata
+1  A: 

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