Order of iteration differs in IE9

2020-04-16 09:17发布

问题:

In IE9, the numeric keys of object properties are sorted and that results in different order of iteration in IE9 compared to IE8 where the order is preserved as it is inserted.

var obj = {
  "5": "John",
  "1": "Kumar",
  "3": "Rajesh",
  "2": "Yogesh"
}

for(var key in obj) alert(key) 

Result

//1,2,3,4 in IE9

//5,1,3,2 in IE8, IE7

Is there anyway I can disable this auto sorting by IE9. If not then is it possible to somehow make the browser understand that the keys should be identified as strings rather than number (but without appending any space, _ or any other special characters)

Please suggest!!

Here is the sample code snippet where I am facing this problem.

    function Person(id, name) {
    this.id = id;
    this.name = name;
}

var persons = new Object();

var p1 = Person("5","John")
persons[5]=p1
var p2 = Person("1","Kumar")
persons[1]=p2  
var p3 = Person("3","Rajesh")
persons[3]=p3
var p4 = Person("4","Yogesh")
persons[4]=p4


for(var id in personId){
   var p = persons[id];
   var option = new Option(p.name, p.id);
   select.options[select.options.length] = option;
}

The select options generated by this script was sorted as per the ID in IE9 where I need the same order in which it is inserted.

回答1:

Property enumeration order is undefined in ECMAScript up to and including version 5 (the current version at time of writing) and does vary between browsers, so you shouldn't rely on any specific ordering. If you need predictable ordering, use an array and a for or while loop. For your example, one option would be:

var arr = [
  {rank: "5", name: "John"},
  {rank: "1", name: "Kumar"},
  {rank: "3", name: "Rajesh"},
  {rank: "2", name: "Yogesh"}
];

for (var i = 0; i < arr.length; ++i) alert(arr[i].rank);

One final note: enumeration order when using a for...in loop is not guaranteed for any kind of object, including arrays, so you should always use for or while when order matters.