Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  157] [ 2]  / answers: 1 / hits: 15932  / 14 Years ago, thu, april 15, 2010, 12:00:00

I identified a bug in my code which I hope to solve with minimal refactoring effort. This bug occurs in Chrome and Opera browsers.
Problem:



var obj = {23:AA,12:BB};
//iterating through obj's properties
for(i in obj)
document.write(Key: +i + +Value: +obj[i]);


Output in FF,IE
Key: 23 Value: AA
Key: 12 Value: BB



Output in Opera and Chrome (Wrong)

Key: 12 Value BB

Key: 23 Value AA



I attempted to make an inverse ordered object like this



var obj1={AA:23,BB:12};
for(i in obj1)
document.write(Key: +obj[i] + +Value: +i);


However the output is the same. Is there a way to get for all browser the same behaviour with small changes?


More From » javascript

 Answers
11

No. JavaScript Object properties have no inherent order. It is total luck what order a for...in loop operates.



If you want order you'll have to use an array instead:



var map= [[23, 'AA'], [12, 'BB']];
for (var i= 0; i<map.length; i++)
document.write('Key '+map[i][0]+', value: '+map[i][1]);

[#97063] Monday, April 12, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kayden

Total Points: 546
Total Questions: 102
Total Answers: 95

Location: Virgin Islands (U.S.)
Member since Fri, Mar 4, 2022
2 Years ago
;