Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome and probably Opera sort object properties automatically

Tags:

javascript

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

like image 711
setty Avatar asked Feb 03 '11 12:02

setty


2 Answers

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.

like image 72
Felix Kling Avatar answered Oct 15 '22 14:10

Felix Kling


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.

like image 24
lonesomeday Avatar answered Oct 15 '22 15:10

lonesomeday