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

后端 未结 2 1576
无人共我
无人共我 2021-01-03 03:06

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 d

相关标签:
2条回答
  • 2021-01-03 03:46

    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.

    0 讨论(0)
  • 2021-01-03 03:47

    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.

    0 讨论(0)
提交回复
热议问题