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

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

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

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


当前回答

下面的'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;
   }
}

其他回答

提升 Const移动= [200,450,- 400,3000,-650,- 130,70,1300];

如果返回值小于0,则A将在B之前 如果返回值是> 0,那么B会在A之前

 movements.sort((a, b) => {
      if (a > b) return 1; //- (Switch order)
      if (a < b) return -1; //- (Keep order)
    });

A -当前值,b -下一个值。

下行 运动。排序((a, b) => { If (a > b)返回-1;// - (Keep) 如果(a < b)返回1;// - (Switch) });

! 改进,最佳解决方案!

movements.sort ((a, b) => a - b); // Same result!

如果a < b是负数(开关) 如果a < b是负数(Keep)

为了创建这种排序,你必须传递一个函数来检查哪个先出现。

在函数中定义你想检查的值:a.id - a.id

const myJson = [ {id: 1, name: 'one'}, {id: 4, name: 'four'}, {id: 2, name: ' 2 '}, {id: 3, name: ' 3 '} ]; //提供要检查的sort方法 const myNewSort = myJson。排序(函数(a, b) { 返回a.id - b.id; }); console.log('my new sort',myNewSort)

基于以上所有的答案,它们也可以像这样在一行中完成:

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

//outputs: 99, 104, 140000

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

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

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

numArray = numArray.sort(sortNumber);

试试下面的代码

var a = [5, 17, 29, 48, 64, 21];
function sortA(arr) {
return arr.sort(function(a, b) {
return a - b;
})
;} 
alert(sortA(a));