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 |
我:你可以重写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></