试图从一个只包含整数的数组中获得最大值和最小值似乎比我想象的要难。

var numArray = [140000, 104, 99]; numArray = numArray.sort(); console.log(numArray)

我希望这是99 104 140000。相反,它显示的是104、14万、99。看起来排序是把值当做字符串处理的。

有没有办法让排序函数对整数值进行排序?


当前回答

你可以简单地排序数字数组

常量数字=[13,17,14,19,16]; 让温度; for(let i=0;i<num.length;i++){ for(let j=i+1;j<num.length;j++){ if(num[i]>num[j]){ 温度=数字[i] 数字[i]=数字[j] 数字[j]=温度 } } } 控制台.log(数字);

其他回答

下面的'numerically'函数作为回调函数提供时,在许多情况下用于对数字数组进行数字排序:

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

array.sort(numerically); 

但在一些罕见的情况下,数组包含非常大的负数,当a-b小于JavaScript可以处理的最小数字时,可能会发生溢出错误。

所以用数字表示函数的更好方法如下:

function numerically(a, b){
   if(a < b){
      return -1;
   } else if(a > b){
      return 1;
   } else {
      return 0;
   }
}

sort_mixed

Object.defineProperty(Array.prototype,"sort_mixed",{
    value: function () { // do not use arrow function
        var N = [], L = [];
        this.forEach(e => {
            Number.isFinite(e) ? N.push(e) : L.push(e);
        });
        N.sort((a, b) => a - b);
        L.sort();
        [...N, ...L].forEach((v, i) => this[i] = v);
        return this;
    })

try a =[1,'u',"V",10,4,"c"," a "].sort_mixed();console.log (a)

在JavaScript中,sort()方法的默认行为是对数组中的值按字母顺序排序。

要按数字排序,你必须定义一个数值排序函数(这很简单):

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

numArray = numArray.sort(sortNumber);

Let grade =[80,100,50,90,40]; grade.sort ((x, y) = > x - y); grade.forEach(元素= > console.log(元素));

数组中。Sort默认执行字典排序,对于数字排序,提供自己的函数。这里有一个简单的例子:

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

numArray.sort(compareNumbers);

还要注意,排序是“就地”工作的,不需要赋值。