Article From:https://www.cnblogs.com/superSmile/p/9122940.html

First, is JS object output in sequence when it traverses output?

  The next step is to practice it.

var obj={'3':'ccc',name:'abc',age:23,school:'sdfds',class:'dfd',hobby:'dsfd'};
Object.keys(obj)

Output: [“3”, “name”, “age”, “school”, “class”, “hobby”);

Change the order of objects,

var obj={name:'abc','3':'ccc',age:23,school:'sdfds',class:'dfd',hobby:'dsfd'};
Object.keys(obj)

Output: [“3”, “name”, “age”, “school”, “class”, “hobby”).

So, the traversing output of the object is not in the order of order, so what rules do it follow, and you will find that you will find that this is also related to the browser, Chrome is not the same as IE, so give the following conclusions:

Chrome Opera The JavaScript parsing engine follows the new version of ECMA-262 fifth specification. Therefore, traversing Book attributes when using for-in statements to traverse object properties is not attribute building order.
The JavaScript parsing engine of IE6 IE7 IE8 Firefox Safari follows the older ECMA-262 third version of the specification, and the order of attribute traversal is determined by the order of attribute construction.

Chrome Opera Using for-in statements to traverse object properties follows a rule:
They first extract the attributes of all key’s parseFloat values as non negative integers, then first traverse the attributes according to the digital order, and then traverse all the remaining attributes in the order of the object definition.

So, what about the solution?

The object can be extracted from the object by Object.keys into an array, then the array is sorted, then the array is traversed, and the attribute value of the object is removed by the key.

Two, JS array traversal sorting method

  We all know that the traversal of an array is in the order of order, so when a lot of objects are placed in an array, how do you want to sort the array according to an attribute of the object?

  1.Define a method:

var compare = function (prop) {
    return function (obj1, obj2) {
        var val1 = obj1[prop];
        var val2 = obj2[prop];if (val1 < val2) {
            return -1;
        } else if (val1 > val2) {
            return 1;
        } else {
            return 0;
        }            
    } 
}
var arr=[{ name:"wlz", age:25},{ name:"wlz", age:5},{ name:"wlz", age:15},{ name:"wlz", age:3},{ name:"zlw", age:24}];
console.log(arr.sort(compare('age')))

Finally, the array is sorted according to its properties.

 

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *