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

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

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

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


当前回答

As sort方法将数组元素转换为字符串。因此,下面的方法也适用于十进制数的数组元素。

let productPrices = [10.33, 2.55, 1.06, 5.77];
console.log(productPrices.sort((a,b)=>a-b));

并给出预期结果。

其他回答

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

在函数中定义你想检查的值: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)

默认情况下,sort方法按字母顺序对元素排序。要进行数字排序,只需添加一个处理数字排序的新方法(sortNumber,如下所示)

var numArray = [140000, 104, 99]; numArray.sort(function(a, b) { 返回 A - B; }); console.log(numArray);

文档:

Mozilla Array.prototype.sort()建议对不包含Infinity或NaN的数组使用这个比较函数。(因为∞-∞是NaN,不是0)。

还有按键排序对象的例子。

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

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

常量数字=[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(数字);

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