1

In Firefox the output is ordered Alphabetically (which is the order they are declared). In IE and Chrome they are numerical. All latest versions.

Which is correct?

<html>
<head></head>
<body>
<script type="text/javascript">
function makeArray()
{
    var array = [{5:'Five',4:'Four',1:'One',3:'Three',2:'Two'}];
    var msg = '';

    for (var val in array[0])
    {
        msg = msg + val;
    }   
    alert(msg);
}
</script>
<input type="button" onClick="makeArray();" value="Press Me" />
</body>
</html>

Back Story... In SpiraTeam (Our current bug tracking system) many of the lists (users, modules, etc) are ordered using a similar format to the above. This makes finding stuff very hard and annoying unless you use FireFox. My interest is purely academical, I only ask because I want to know which browser's correct.

DaveShaw
  • 48,792
  • 16
  • 106
  • 133
  • There's actually only one item in the array - and object with 5 properties. So I think the correct way to phrase the question is "what is the correct ordering of properties in an object?" – selbie Oct 03 '11 at 20:25
  • You can find more info about order of iteration in a object here http://stackoverflow.com/questions/280713/elements-order-in-a-for-in-loop/280861#280861 – Narendra Yadala Oct 03 '11 at 20:25
  • 2
    Duplicate? http://stackoverflow.com/questions/280713/elements-order-in-a-for-in-loop – Ryan Kinal Oct 03 '11 at 20:27

2 Answers2

5

Actually you are asking: what is the order of properties within object literal when iterating using for loop? The array is irrelevant here.

And the answer is: it is unspecified. Most of the time it will be the same as you see in the code, but there is no guarantee.

This question has been asked hundreds of times:

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 311,858
  • 65
  • 665
  • 652
1

Your issue seems to be that you are not iterating over an Array, but an Object...

ECMA doesn't seem to define in step 5 how to go about this... (alphabetically, numerically etc)

stevebot
  • 21,481
  • 26
  • 107
  • 176