如何正确排序整数数组 [英] How to sort an array of integers correctly
问题描述
试图从我知道只包含整数的数组中获取最高和最低值似乎比我想象的更难.
Trying to get the highest and lowest value from an array that I know will contain only integers seems to be harder than I thought.
var numArray = [140000, 104, 99];
numArray = numArray.sort();
console.log(numArray)
我希望它显示 99、104、140000
.相反,它显示 104, 140000, 99
.所以看起来排序是将值作为字符串处理.
I'd expect this to show 99, 104, 140000
. Instead it shows 104, 140000, 99
. So it seems the sort is handling the values as strings.
有没有办法让排序函数对整数值进行实际排序?
Is there a way to get the sort function to actually sort on integer value?
推荐答案
默认情况下,sort 方法按字母顺序对元素进行排序.要对数字进行排序,只需添加一个处理数字排序的新方法(sortNumber,如下所示)-
By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -
var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
return a - b;
});
console.log(numArray);
文档:
Mozilla Array.prototype.sort()
建议对不包含无穷大或 NaN 的数组使用此比较函数.(因为 Infinity - Infinity
是 NaN,而不是 0).
Mozilla Array.prototype.sort()
recommends this compare function for arrays that don't contain Infinity or NaN. (Because Infinity - Infinity
is NaN, not 0).
还有按键排序对象的例子.
Also examples of sorting objects by key.
这篇关于如何正确排序整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!