IE9中的迭代顺序不同 [英] Order of iteration differs in IE9

查看:130
本文介绍了IE9中的迭代顺序不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在IE9中,对象属性的数字键被排序,并且与IE8相比,IE9中的迭代顺序不同,IE8在插入时保留了顺序。

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) 

结果

// IE9中的1,2,3,4

//1,2,3,4 in IE9

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

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

无论如何,我可以通过IE9禁用此自动排序。如果没有,则可以以某种方式使浏览器理解密钥应该被识别为字符串而不是数字(但不附加任何空格,_或任何其他特殊字符)

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)

请建议!!

以下是我遇到此问题的示例代码段。

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;
}

此脚本生成的选项按照IE9中的ID进行排序我需要插入相同的顺序。

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.

推荐答案

在ECMAScript中包含版本5(包括版本5)中的属性枚举顺序未定义(在撰写本文时的当前版本)并且浏览器之间的版本有所不同,因此您不应该依赖任何特定的排序。如果您需要可预测的排序,请在循环时使用数组和表示。对于您的示例,一个选项是:

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);

最后一个注释:使用 for ... in <时的枚举顺序/ code>对于任何类型的对象(包括数组)都不保证循环,因此在时应始终使用表示 $ c>当订单很重要时。

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.

这篇关于IE9中的迭代顺序不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆