tags:

views:

37

answers:

2

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?

+6  A: 

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]);
bobince
To elaborate, this is because Javascript objects are hashes (think Hash Tables). If you want ordering, use an array.
Matt Ball
Agreed, added example.
bobince
well this happens when programmers writes without deep understanding what he is writting :).
Jenea
Pesky programmers! I hate them! :-)
bobince
+1  A: 

I think you'll find the only reliable way to do this would be to use an array rather than an associative array, eg:

var arr = [{key:23,val:"AA"},{key:12,val:"BB"}];
for(var i=0; i<arr.length; i++)
  document.write("Key: "+arr[i].key +" "+"Value: "+arr[i].val);
Graza
JavaScript has objects with properties, not associative arrays. If they were arrays, they would be ordered.
Álvaro G. Vicario
Agreed - but objects with properties are often (not entirely correctly I'll admit) called "associative arrays", or at least *used* for that purpose. "Associative arrays" (in a more general, not javascript sense) are usually not considered to equate to ordered values - they are considered to be a collection of name/value pairs.
Graza