为什么Javascript sort()函数没有给出预期的输出? [英] Why Javascript sort() function is not giving the expected output?
本文介绍了为什么Javascript sort()函数没有给出预期的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
排序不使用整数?
如何在javascript排序方法中对数字进行排序
Array.sort()不能正确排序数字
代码:
var x = [40,100,1,5,25,10];
x.sort();
输出:
1,10,100,25,40,5
我的预期产量:
1,5,10,25,40,100
推荐答案
JavaScript数组 .sort()
函数默认情况下将数组元素转换为字符串比较。
The JavaScript Array .sort()
function by default converts the array elements to strings before making comparisons.
您可以覆盖:
x.sort(function(e1, e2) { return e1 - e2; });
(传递的函数应该返回一个负数,零或正数,根据是否为第一个元素小于,等于或大于第二个元素。)
(The function passed should return a number that's negative, zero, or positive, according to whether the first element is less than, equal to, or greater than the second.)
我从未见过这种奇怪方面的理由。
I've never seen a rationale for this odd aspect of the language.
这篇关于为什么Javascript sort()函数没有给出预期的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文