Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

javascript - 如何正确排序整数数组(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(); alert(numArray) 

I'd expect this to show 99, 104, 140000 .

(我希望它显示99, 104, 140000 。)

Instead it shows 104, 140000, 99 .

(而是显示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函数对整数值进行实际排序?)

  ask by peirix translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

By default, the sort method sorts elements alphabetically.

(默认情况下,sort方法按字母顺序对元素进行排序。)

To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -

(要进行数字排序,只需添加一个处理数字排序的新方法(sortNumber,如下所示)-)

 function sortNumber(a, b) { return a - b; } var numArray = [140000, 104, 99]; numArray.sort(sortNumber); console.log(numArray); 

In ES6, you can simplify this with arrow functions:

(在ES6中,您可以使用箭头功能简化此操作:)

numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort

Documentation:

(说明文件:)

Mozilla Array.prototype.sort() recommends this compare function for arrays that don't contain Infinity or NaN.

(Mozilla Array.prototype.sort()建议此比较功能用于不包含Infinity或NaN的数组。)

(Because Inf - Inf is NaN, not 0).

((因为Inf - Inf是NaN,而不是0)。)

Also examples of sorting objects by key.

(还有按键对对象进行排序的示例。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...