JavaScript数组排序功能无法正确排序 [英] Javascript Array Sort function not sorting properly
本文介绍了JavaScript数组排序功能无法正确排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对javascript的sort()函数有疑问
I have a question regarding javascript's sort() function
var arr = [23,43,54,2,3,12];
arr.sort();
其输出为 [12,2,23,3,43,54 ]
好,应该是 [2、3、12、23、43、54]
?
推荐答案
这是因为您正在使用默认的排序算法对数字进行排序,该算法会将它们转换为字符串并按字典顺序进行排序。
It's because you're sorting the numbers with the default sorting algorithm, which converts them to a string and sorts lexicographically.
而是通过其返回值传递定义排序顺序的函数。
Instead pass a function defining a sort order via its return value.
= snippet data-lang = js data -hide = false data-console = true data-babel = false>
var arr = [23,43,54,2,3,12];
console.log(arr.sort((a, b) => a - b));
返回正数会将 a
移到列表末尾。
Returning a positive number moves a
toward the end of the list.
这篇关于JavaScript数组排序功能无法正确排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文