Chrome sorts objects by keywords

Possible duplicate:
Chrome and possibly Opera's sort object properties automatically

I have a very simple code:

var obj = {3:'a',2:'b',1:'c'}; console.log(obj); 

In Firefox 4.0.1, it returns:

 Object { 3="a", 2="b", 1="c"} 

In Chrome 11.0.696.71 it returns:

 Object { 1="c", 2="b", 3="a"} 

How can I make Chrome not sort this object?

+4
source share
2 answers

This is a known bug / chrome feature. Even the jQuery author is indignant, but the chrome guys remain inflexible, saying that this is a β€œfeature”: http://code.google.com/p/chromium/issues/detail?id=883 [1]

As a workaround, use arrays or some sort of MixedCollection (as in extjs) or something similar.

 null !== true and also null !== false // in php and js it so 

[1]: John Resig (jeresig) is the author of jquery

+2
source

For objects, the specification is that the order of the elements is not preserved. In other words, javascript does not guarantee any specific order for object properties.

You will need to use an array if you want to keep the order of the elements. In this case, your object can be rewritten to:

 var arrobj = ['c','b','a']; 

or

 var arrobj = ['a','b','c'].reverse(); 

Given that the first index of the element will be 0 (zero)

+4
source

All Articles