数组方法 sort() 排序错乱问题

一、问题

在JavaScript中,数组使用sort()后发现有排序不正确的情况,如下:

let arr = [1, 2, 3, 10, 20, 30]
arr.sort()
console.log(arr) // [1, 10, 2, 20, 3, 30]

二、原因

其实,sort方法会调用每个数组元素的toString方法得到字符串,然后再根据Unicode编码对得到的字符串进行排序。

// toString后
['1', '2', '3', '10', '20', '30']

// 对应的Unicode编码
['49', '50', '51', '49', '50', '51']

// 排序
['49', '49', '50', '50', '51', '51']

// 对应数组元素
[1, 10, 2, 20, 3, 30]

三、解决办法 

显然,这种结果不是我们想要的,这时,sort()方法的参数就起到了作用,我们把这个参数叫做比较函数

let arr = [1, 2, 3, 10, 20, 30]

//比较函数—升序
let compare = (x, y) => {
    if (x < y) {
        return -1;
    } else if (x > y) {
        return 1;
    } else {
        return 0;
    }
}
console.log(arr.sort(compare)) // [1, 2, 3, 10, 20, 30]

//比较函数—降序
let compare = (x, y) => {
    if (x < y) {
        return 1;
    } else if (x > y) {
        return -1;
    } else {
        return 0;
    }
}
console.log(arr.sort(compare)) // [30, 20, 10, 3, 2, 1]

可以简化为以下常用方法

let arr = [1, 2, 3, 10, 20, 30]

//升序
arr.sort((a, b) => {
    return a - b;
})

//降序
arr.sort((a, b) => {
    return b - a;
});

文章每周持续更新,可以微信搜索「 前端大集锦 」第一时间阅读,回复【视频】【书籍】领取200G视频资料和30本PDF书籍资料

猜你喜欢

转载自blog.csdn.net/qq_38128179/article/details/108993557