How to iterate javascript object properties in the order they were written.

Posted by Jenea on Stack Overflow See other posts from Stack Overflow or by Jenea
Published on 2010-04-15T16:37:33Z Indexed on 2010/04/15 16:43 UTC
Read the original article Hit count: 263

Filed under:

Hi. 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?

© Stack Overflow or respective owner

Related posts about JavaScript