如何在Javascript中对数组中的数字进行排序[重复]

时间:2022-04-05 16:00:53

This question already has an answer here:

这个问题在这里已有答案:

var set = [3,100, 70, 55, 47, 202];
var sortedNumbers = set.sort();
console.log(sortedNumbers)

I see the following in the console:

我在控制台中看到以下内容:

[100, 202, 3, 47, 55, 70]

Why isn't the array sorted?

为什么数组不排序?

1 个解决方案

#1


0  

The sort function treats the array values as strings. Instead you could use:

sort函数将数组值视为字符串。相反,你可以使用:

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

    var sortedNumbers = set.sort(sortNumber);

#1


0  

The sort function treats the array values as strings. Instead you could use:

sort函数将数组值视为字符串。相反,你可以使用:

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

    var sortedNumbers = set.sort(sortNumber);