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

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

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

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


当前回答

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

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

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

numArray = numArray.sort(sortNumber);

其他回答

如果有人不理解Array.sort()如何处理整数,请阅读这个答案。

字母顺序排列:

默认情况下,sort()方法将值按字母和升序排列为字符串。

const myArray = [104, 140000, 99];
myArray.sort();
console.log(myArray); // output is [104, 140000, 99]

使用array.sort(compareFunction)的升序:

const myArray = [104, 140000, 99];
myArray.sort(function(a, b){
  return a - b;
});
console.log(myArray); // output is [99, 104, 140000]

w3schools的解释:

compareFunction定义了一个可选的排序顺序。函数应该返回一个负的、零的或正的值,这取决于参数,比如: 函数(a, b){返回a-b} 当sort()方法比较两个值时,它将值发送给compare函数,并根据返回值(负、零、正)对值进行排序。 例子: 当比较40和100时,sort()方法调用compare 函数(40100)。 该函数计算40-100,并返回-60(负值)。 sort函数将把40排序为低于100的值。

使用array.sort(compareFunction)按降序排列:

const myArray = [104, 140000, 99];
myArray.sort(function(a, b){
  return b - a;
});
console.log(myArray); // output is [140000, 104, 99]

这一次我们用b - a(即。, 100-40),返回正值。

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

试试下面的代码

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

提升 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)

对整数> 0排序,跳出框框思考:

函数sortArray(arr) { return new Promise((resolve) => { Const result = [] arr.forEach((item) => { setTimeout(() => { result.push(项) 如果结果。长度== arrr . Length) resolve(result) },项) }) }) } sortArray([4,2, 42岁,128年,56岁的2]),然后((结果)= > { document . write (JSON.stringify(结果)) })

请注意,这不应该有效地使用,.sort()更适合于此,检查其他答案