JavaScript中sort()函数的排序逻辑

在JavaScript中sort()函数默认会把数组的元素转换成字符串,然后再进行排序。如果,数组中的元素是 number 类型的,那么得到结果可能和我们想的不一样。
举例如下:

arr = [50, 90, 1, 10, 2];
// 比如 arr 数组直接使用 sort() 方法进行排序时,会把该数组中的每个元素都转化成字符串,然后再进行排序得到的结果为:[1, 10, 2, 50, 90]
// 我们期望的结果是:[1, 2, 10, 50, 90];

那么,怎么样才能让数组 arr 使用 sort() 方法后得到想要的结果呢?在使用 sort() 方法对 arr 数组进行排序时需要传入一个函数作为其参数。具体示例如下所示[1]

// 需要排序的数组
var arr = [50, 90, 1, 10, 2];

// 按照升序对arr中的元素进行排列的方法
arr = arr.sort((current, next) => {
	// 即按升序排序
	return current - next;
});

// 上述代码使用sort()方法进行排序的实际思路如下所示:
// 1. current = 50, next = 90
//    current - next = 50 - 90 = -40
//    由于 (current - next) 的结果为负数,因此无需变数组元素的索引位置,此时经过排序后的数组如下所示:
//    [50, 90, 1, 10, 2];

// 2. current = 90, next = 1
//    current - next = 90 - 1 = 89
//    由于 (current - next) 的结果为正数,因此需要改变数组元素的索引位置,此时经过排序后的数组如下所示:
//    [50, 1, 90, 10, 2];

// 3. 此时,sort()会判断,arr 数组中 90 前面的两个元素是否进行过比较。如果没有进行过比较,则需要进行比较处理。即:
//    此时,需要比较的数组元素为 50 和 1,即
//    current = 50, next = 1
//    current - next = 50 - 1 = 49
//    由于 (current - next) 的结果为正数,因此需要改变数组元素的索引位置,此时经过排序后的数组如下所示:
//    [1, 50, 90, 10, 2];

// 4. sort()能够识别数组中的两个元素是否已经进行过比较,如果已经进行过比较那么不会重复再比较一次。此时,current 和 next 的值如下所示:
//    current = 90, next = 10
//    current - next = 90 - 10 = 80
//    由于 (current - next) 的结果为正数,因此需要改变数组元素的索引位置,此时经过排序后的数组如下所示:
//    [1, 50, 10, 90, 2];

// 5. current = 50, next = 10
//    current - next = 50 - 10 = 40
//    由于 (current - next) 的结果为正数,因此需要改变数组元素的索引位置,此时经过排序后的数组如下所示:
//    [1, 10, 50, 90, 2];

// 6. current = 1, next = 10
//    current - next = 1 - 10 = -9
//    由于 (current - next) 的结果为负数,因此无需改变数组元素的索引位置,此时经过排序后的数组如下所示:
//    [1, 10, 50, 90, 2];

// 7. current = 90, next = 2
//    current - next = 90 - 2 = 89
//    由于 (current - next) 的结果为正数,因此需要改变数组元素的索引位置,此时经过排序后的数组如下所示:
//    [1, 10, 50, 2, 90];

// 8. current = 50, next = 2
//    current - next = 50 - 2 = 48
//    由于 (current - next) 的结果为正数,因此需要改变数组元素的索引位置,此时经过排序后的数组如下所示:
//    [1, 10, 2, 50, 90];

// 9. current = 10, next = 2
//    current - next = 10 - 2 = 8
//    由于 (current - next) 的结果为正数,因此需要改变数组元素的索引位置,此时经过排序后的数组如下所示:
//    [1, 2, 10, 50, 90];

// 10. current = 1, next = 2
//    current - next = 1 - 2 = -1
//    由于 (current - next) 的结果为负数,因此无需改变数组元素的索引位置,此时经过排序后的数组如下所示:
//    [1, 2, 10, 50, 90];
// 自此,使用sort()函数对数组中元素为number类型的数组完成了升序排序。如果要进行降序排列,那么,只需要把 current - next 修改 next - current 即可。

参考文章:

[1] https://stackoverflow.com/questions/3423394/algorithm-of-javascript-sort-function
[2]JavaScript的sort()方法的底层实现:https://github.com/v8/v8/blob/ad82a40509c5b5b4680d4299c8f08d6c6d31af3c/src/js/array.js的第710行

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值