关于排序:为什么Javascript sort()函数没有给出预期的输出?

Why Javascript sort() function is not giving the expected output?

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

Possible Duplicate:
sort not working with integers?
How to sort number in javascript sort method
Array.sort() doesn't sort numbers correctly

代码:

1
2
var x = [40,100,1,5,25,10];
x.sort();

输出:

1
1,10,100,25,40,5

我的预期输出:

1
1,5,10,25,40,100


.sort()function by the JavaScript数组的数组元素的默认converts strings to before制作比较。P></

我:你可以重写P></

1
x.sort(function(e1, e2) { return e1 - e2; });

(passed should the number函数返回到零,或是消极的,积极的,根据是否第一元is the less equal to,the second,比前更大。)P></

我从来没有见过在奇数显示原理for this of the language。P></


根据array.sort MDNP></

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or"telephone book," not numerical) order. For example,"80" comes before"9" in lexicographic order, but in a numeric sort 9 comes before 80.

我知道你做的东西:should be likeP></

1
2
3
4
5
6
function compareNumbers(a, b)
{
  return a - b;
}
var x = [40,100,1,5,25,10];
x.sort(compareNumbers);


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

安恩alphabetical does the character,ascending类(1 sorting is…_ _ 1,1,1,2 _,5)提供默认出现在布尔函数as that changes行为P></

更多信息:can be found here www.w3schools.com http:/ / / / jsref jsref _ sort.aspP></