本文介绍了如何正确排序的整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图从一个阵列的最高值和最低值,我知道将只包含整数似乎比我想象的更难?

Trying to get the highest and lowest value from a 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[0] + ", " + numArray[numArray.length - 1]);

我预计这将显示99,140000。相反,它显示104 99。如此看来,这种排序是处理值作为字符串?

I'd expect this to show "99, 140000". Instead it shows "104, 99". So it seems the sort is handling the values as strings?

什么办法让排序函数实际上排序整数价值?

Any way to get the sort function to actually sort on integer value?

推荐答案

默认情况下,排序方法字母顺序​​排列的元素。要排序数字只是添加用于处理数字排序的新方法(sortNumber,如下图所示) -

By default the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -

function sortNumber(a,b) {
    return a - b;
}

var numArray = [140000, 104, 99];
numArray.sort(sortNumber);
alert(numArray.join(","));

这篇关于如何正确排序的整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 03:46