关于javascript:Array.sort()没有正确排序数字

Array.sort() doesn't sort numbers correctly

本问题已经有最佳答案,请猛点这里访问。

在Chrome14和火狐5(还没有测试其他浏览器)中,以下代码对数字排序不正确:

1
2
3
4
5
6
7
8
9
a = new Array();
a.push(10);
a.push(60);
a.push(20);
a.push(30);
a.push(100);


document.write(a.sort())

它返回10100,20,30,60

我尝试过不同的数字,它总是表现得好像0不在那里,否则就对数字进行正确的排序。有人知道为什么吗?


1
a.sort(function(a,b){return a - b})

这些可能会令人困惑……查看此链接。


I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?

您将得到一个字典式排序(例如,将对象转换为字符串,并按字典顺序排序),这是JavaScript中的默认排序行为:

https://developer.mozilla.org/en/javascript/reference/global_objects/array/sort

1
array.sort([compareFunction])

Parameters

compareFunction

Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

在ECMAScript规范(通用javascript的规范性参考)中,ECMA-262,第3版,第15.4.4.11节,默认排序顺序是词典编纂的,尽管它们不会出来说出来,而是给出调用给定比较函数的概念排序函数的步骤(如有必要),否则比较参数转换为字符串时:

1
2
3
4
5
6
7
8
13. If the argument comparefn is undefined, go to step 16.
14. Call comparefn with arguments x and y.
15. Return Result(14).
16. Call ToString(x).
17. Call ToString(y).
18. If Result(16) < Result(17), return ?1.
19. If Result(16) > Result(17), return 1.
20. Return +0.


javascript中数组的默认排序是按字母顺序搜索。如果需要数字排序,请尝试如下操作:

1
2
var a = [ 1, 100, 50, 2, 5];
a.sort(function(a,b) { return a - b; });


您可以使用排序函数:

1
2
3
var myarray=[25, 8, 7, 41]
myarray.sort( function(a,b) { return b - a; } );
// 7 8 25 41

查看http://www.javascriptkit.com/javautors/arraysort.shtml


试试这个:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
a = new Array();
a.push(10);
a.push(60);
a.push(20);
a.push(30);
a.push(100);
a.sort(Test)

document.write(a);


function Test(a,b)
{
    return a > b ? true : false;
}