12

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

Luc125
5,87736 silver badges35 bronze badges
asked Feb 3, 2011 at 12:45
1

2 Answers 2

18

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.

answered Feb 3, 2011 at 12:50
Sign up to request clarification or add additional context in comments.

1 Comment

there is no specification that defines in which order properties should be enumerated ..... I have an idea. How about the order WE PUT THEM IN.
5

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.

answered Feb 3, 2011 at 12:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.