为什么javascript的排序功能不能正常工作?

Chr*_*sis 12 javascript arrays sorting

这个简单的javascript

var x = new Array();
x[0] = 2.73;
x[1] = 11.17;
x[2] = 3.12
x.sort();

for(var i in x)
    alert(x[i]);
Run Code Online (Sandbox Code Playgroud)

产生结果: 11.17, 2.73, 3.12而不是2.73, 3.12, 11.17.

为什么这样,我该如何解决?

提前致谢!

Tom*_*Tom 17

按字母顺序排序,尝试传递自己的排序功能:

var x = new Array();
x[0] = 2.73;
x[1] = 11.17;
x[2] = 3.12;

numberSort = function (a,b) {
    return a - b;
};

x.sort(numberSort);

for(var i in x) {
    alert(x[i]);
}
Run Code Online (Sandbox Code Playgroud)


sje*_*397 9

默认情况下,Array.sort将按字母顺序(lexographically)排序...但您可以提供自己的功能.尝试:

x.sort(function(a, b) { return a > b ? 1 : -1});
Run Code Online (Sandbox Code Playgroud)

  • 人们也可以写`return ab`,因为只返回值的符号很重要. (4认同)
  • @ sje397:恩,我这么说,但是实际上这并不完全安全:如果a-b返回的数字大于Number.MAX_VALUE或小于-Number.MAX_VALUE,那么它可能会中断。虽然有点边缘情况。 (2认同)

小智 5

Array.sort() 函数将其元素视为字符串,如果没有函数传递给 sort() 语句,它会将元素转换为 Unicode 并进行排序。因此,建议在对数字进行排序时传递自定义排序函数。

function customSort(a, b){
     return a - b; 
}
console.log([-11,-2, 0 ,100].sort(customSort));
Run Code Online (Sandbox Code Playgroud)

此 customSort() 函数将以升序对数组 in_place 进行排序。