var obj = {
'51' : { 'name':'name1'},
'66' : { 'name':'name2'},
'58' : { 'name':'name3'}
};
$(function() {
s = '';
$.each(obj, function(k, v) {
s += ' '+k;
});
alert(s);
});
In IE and Firefox it's 51 66 58, but in Opera and Chrome it's 51 58 66 Why Jquery.each() sort by key in opera, chrome? What can i do to keep native order?
p.s if array keys is a string, result 51j 66j 58j perhaps opera and chrome try to convert keys to integer where it's possible
var obj = {
"51j" : { "name":"name1"},
"66j" : { "name":"name2"},
"58j" : { "name":"name3"}
};
-
It's object keys, and they're strings whatever happens.Skilldrick– Skilldrick2010年08月25日 09:35:16 +00:00Commented Aug 25, 2010 at 9:35
-
it's seems opera and chrome do not think so..ncs– ncs2010年08月25日 09:49:01 +00:00Commented Aug 25, 2010 at 9:49
-
In JS, obj[1] and obj['1'] are equivalent. However, as already explained the order of for..in iteration is left undefined by the specification. Browsers can return the values in ANY order and still behave "correctly" per the specification. Over time, compatibility with the web and other browsers has forced insertion order most of the time, but this is still not reliable as you've discovered.hallvors– hallvors2010年08月27日 03:24:05 +00:00Commented Aug 27, 2010 at 3:24
1 Answer 1
JavaScript objects are unordered. There is no guarantee about which order the keys should come out when you loop over them and JS engines are free to implement whatever storage and retrieval systems they like.
If order matters, use an array: []
This can contain objects:
[
{ 'foo' : '1234', 'bar' : '5678' },
{ 'foo' : 'abcd', 'bar' : 'qwer' },
{ 'foo' : 'ldng', 'bar' : 'plma' }
]
Explore related questions
See similar questions with these tags.