Do you have to use a compare function to sort an array of numbers?

前端 未结 2 381
渐次进展
渐次进展 2021-01-25 07:04

I was under the impression that in order to sort an array of numbers you had to do the following:

var numbers = [4, 1, 2, 3];

function compare(a, b) {
    retur         


        
2条回答
  •  猫巷女王i
    2021-01-25 07:28

    There is a default sort function as stated here:
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

    The default sort order is according to string Unicode code points.

    var scores = [1, 10, 2, 21]; 
    scores.sort(); // [1, 10, 2, 21]
    // Watch out that 10 comes before 2,
    // because '10' comes before '2' in Unicode code point order.
    

    So yes, it will not sort the numbers as you'd like. It will sort them as strings.

    For easy usage you can do the sort function inline:

    numbers.sort(function(a,b){return a - b});
    

提交回复
热议问题