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

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

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

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


当前回答

只需执行.sort((a, b) => a - b),而不是.sort()本身

var numArray = [140000, 104,99]; numArray。排序((a, b) => a - b); console.log (numArray)

其他回答

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

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

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

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

知道更多

我同意aks,但是不用

return a - b;

你应该使用

return a > b ? 1 : a < b ? -1 : 0;

默认情况下,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 compareNumbers = (a: number, b: number): number => a - b

myArray.sort(compareNumbers)

sort_mixed

Object.defineProperty(Array.prototype,"sort_mixed",{
    value: function () { // do not use arrow function
        var N = [], L = [];
        this.forEach(e => {
            Number.isFinite(e) ? N.push(e) : L.push(e);
        });
        N.sort((a, b) => a - b);
        L.sort();
        [...N, ...L].forEach((v, i) => this[i] = v);
        return this;
    })

try a =[1,'u',"V",10,4,"c"," a "].sort_mixed();console.log (a)