JavaScript中sort()函数的排序逻辑
2026/7/28 14:52:02 网站建设 项目流程

在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]:

// 需要排序的数组vararr=[50,90,1,10,2];// 按照升序对arr中的元素进行排列的方法arr=arr.sort((current,next)=>{// 即按升序排序returncurrent-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行

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询