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

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

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

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


当前回答

您可以简单地使用max()和min()内置函数来获得高度和最小值

var numArray = [140000, 104, 99];
console.log(Math.max(...numArray));
console.log(Math.min(...numArray));

如果你想按升序或降序排序

numArray.sort((a, b)=> a - b);

知道更多

其他回答

试试下面的代码

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

您可以简单地使用max()和min()内置函数来获得高度和最小值

var numArray = [140000, 104, 99];
console.log(Math.max(...numArray));
console.log(Math.min(...numArray));

如果你想按升序或降序排序

numArray.sort((a, b)=> a - b);

知道更多

提升

arr.sort((a, b) => a - b);

下行

arr.sort((a, b) => b - a);

只是为了好玩:

降序=升序+反转

arr.sort((a, b) => a - b).reverse();

排序函数的行为如此怪异的原因

从文档中可以看到:

[…数组根据每个字符的Unicode码位排序 值,根据字符串转换每个元素。

如果你打印数组的unicode点值,那么它就会被清除。

console.log(“140000”.charCodeAt (0)); console.log(“104”.charCodeAt (0)); console.log(“99”.charCodeAt (0)); //请注意,我们只查看数字charCodeAt(0)的第一个索引

返回:“49,49,57”。

49 (unicode value of first number at 140000)
49 (unicode value of first number at 104)
57 (unicode value of first number at 99)

现在,因为140000和104返回了相同的值(49),它切断了第一个索引并再次检查:

console.log(“40000”.charCodeAt (0)); console.log(“04”.charCodeAt (0)); //请注意,我们只查看数字charCodeAt(0)的第一个索引

52 (unicode value of first number at 40000)
40 (unicode value of first number at 04)

如果我们对这个进行排序,那么我们会得到:

40 (unicode value of first number at 04)
52 (unicode value of first number at 40000)

所以104在140000之前。

所以最终的结果是: var numArray = [140000, 104,99]; numArray = numArray.sort(); console.log (numArray)

104, 140,000, 99

结论:

Sort()仅通过查看数字的第一个索引来排序。Sort()并不关心一个整数是否比另一个大,它比较数字的unicode值,如果有两个相同的unicode值,那么它检查是否有下一个数字并进行比较。

要正确排序,必须向sort()传递一个比较函数,就像这里解释的那样。

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

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