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

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

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

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


当前回答

打印稿变体

const compareNumbers = (a: number, b: number): number => a - b

myArray.sort(compareNumbers)

其他回答

如果你需要从字符串列表中计算和排序最大的charCodeAt,这是正确的方法。

const arrayLines = '1.1.1.1\n1.0.1.1\n1.1.1.2\n1.1.1.0'.split('\n');

// Response: (4) ['1.0.1.1', '1.1.1.0', '1.1.1.1', '1.1.1.2']
arrayLines.sort((a, b) => {
    let a_charCodeSize = 0,
        b_charCodeSize = 0;

    // Loop true a & b characters and calculate the charCodeAt size.
    for (const aChar of a) a_charCodeSize += aChar.charCodeAt(0);
    for (const bChar of b) b_charCodeSize += bChar.charCodeAt(0);

    return a_charCodeSize - b_charCodeSize;
});

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

从文档中可以看到:

[…数组根据每个字符的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()传递一个比较函数,就像这里解释的那样。

默认情况下,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)。

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

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

试试下面的代码:

HTML:

<div id="demo"></div>

JavaScript代码:

<script>
    (function(){
        var points = [40, 100, 1, 5, 25, 10];
        document.getElementById("demo").innerHTML = points;
        points.sort(function(a, b){return a-b});
        document.getElementById("demo").innerHTML = points;
    })();
</script>