Change in order for .each() in firefox and chrome

馋奶兔 提交于 2019-11-30 15:54:53

问题


I have a web service that returns a JSON encoded array of data. I then use jQuery's .each() function to iterate through that array but in Firefox it iterates down while in Chrome it iterates up.

the data that come sback from the web service is:

{
  "data": {
    "610": {
      "id": "610",
      "url": "a url 1",
      "description": "XXX YYY",
      "toc": "0000-01-00",
      "active": "1"
    },
    "608": {
      "id": "608",
      "url": "a url 1",
      "description": "ytttgffrr",
      "toc": "0000-01-00",
      "active": "1"
    },
    "607": {
      "id": "607",
      "url": "a url  3",
      "description": "rtretert3",
      "toc": "0000-01-00",
      "active": "1"
    },
    "606": {
      "id": "606",
      "url": "a url 4",
      "description": "xxxwwww",
      "toc": "0000-01-00",
      "active": "1"
    },
    ...
  }
}

Firefox goes 610 -> 606 while chrome fors 606 -> 610.

Any ideas why and what I can do about it?


回答1:


Properties in objects have no inherent order. The ECMAScript specification doesn’t guarantee that for…in statements will traverse the object by its properties in alphabetical order. jQuery.each uses for…in under the hood when used on objects.

If the order is important to you, use an array instead of an object.




回答2:


Property enumeration does not have any guaranteed order. If you want to enumerate over properties in a guaranteed order, put the properites of the object in an array, sort them as you expect and then enumerate over that.

In ES5, you can do this simply using Object.keys();

var keys = Object.keys(yourObj).sort();

for (var i=0;i<keys.length;i++) {
    // use yourObj[keys[i]]; guaranteed to be in the right order
}

If you're not using an HTML5 shim or can't use the Object.keys() polyfiller, a for in will suffice;

var keys = [];

for (var x in yourObj) {
    yourObj.hasOwnProperty(x) && keys.push(x);
}

keys.sort();

for (var i=0;i<keys.length;i++) {
    // use yourObj[keys[i]]; guaranteed to be in the right order
}

Of course, the sort() function on the Array object allows you to specify a function for a custom sort order. You can also use reverse() to reverse the key order.



来源:https://stackoverflow.com/questions/9843142/change-in-order-for-each-in-firefox-and-chrome

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!