Sort sorting problem in JS

sort()
can be used to sort the elements of an array

The original array will be changed, and sorted according to the Unicode encoding by default,
so when sorting numbers, you may get wrong results.

Solution:
Specify the sorting rules yourself.
You can add a callback function to sort() to specify the sorting. The
callback function needs to define two line parameters.

The browser will determine the order of the elements according to the return value of the callback function:
if a value greater than 0 is returned , the elements will exchange positions.
If a value less than 0 is returned , the position of the element remains unchanged.
If a 0 is returned , it is considered two equal elements, it does not change position

//未加回调函数,排序有可能出问题,如下图
var arr = [2, 6, 22, 8, 66, 9];
arr.sort();

console.log(arr);

problem appear

//添加回调函数,得到的结果如下图
var arr2 = [2, 6, 22, 8, 66, 9];
arr2.sort(function (a, b) {
    
    
    if (a > b) {
    
    
        return 1; //前边大,交换位置
    } else if (a < b) {
    
    
        return -1; //前边小,不交换位置
    }else{
    
    
        return 0; //前后相等,不交换位置
    }

    //或者上边的太多,可以直接这样写
    //升序
    //return a-b;
    //降序
    //return b-a;
});

console.log(arr2);

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42524288/article/details/103117916