简体   繁体   English

IE9中的迭代顺序不同

[英]Order of iteration differs in IE9

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. 在IE9中,对象属性的数字键被排序,并且与IE8相比,IE9中的迭代顺序不同,IE8在插入时保留了顺序。

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

for(var key in obj) alert(key) 

Result 结果

//1,2,3,4 in IE9 在IE9中// 1,2,3,4

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

Is there anyway I can disable this auto sorting by IE9. 无论如何我可以通过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. 此脚本生成的选择选项按照IE9中的ID进行排序,其中我需要插入相同的顺序。

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. 属性枚举顺序在ECMAScript中未定义,包括版本5(编写时的当前版本),并且在浏览器之间有所不同,因此您不应该依赖任何特定的顺序。 If you need predictable ordering, use an array and a for or while loop. 如果需要可预测的排序,请使用数组和forwhile循环。 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. 最后一点注意:对于任何类型的对象(包括数组),都不能保证在使用for...in循环时的枚举顺序,因此在订单有用时应始终使用forwhile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM