Algorithm of JavaScript “sort()” Function

前端 未结 8 734
灰色年华
灰色年华 2020-12-02 17:48

Recently when I was working with JavaScript \"sort()\" function, I found in one of the tutorials that this function does not sort the numbers properly. Instead to sort numbe

相关标签:
8条回答
  • 2020-12-02 18:31

    And what if your n is defined as:

    var n = [10, 5, 40, 25, 100, 1]; 
    
    0 讨论(0)
  • 2020-12-02 18:35

    Well, if you are sorting the following list, it contains only strings:

    var n = ["10", "5", "40", "25", "100", "1"];
    

    So I would expect any language would compare them as strings, thus resulting in a sort order of:

    var n = ["1", "10", "100", "25", "40", "5"];
    

    Which necessitates your code to use a custom sort (as you have done) to cast the strings back to integers for the purposes of sorting.

    Edit

    As Pointy mentioned, by default the JavaScript sort() method sorts elements alphabetically, including numbers:

    By default, the sort() method sorts the elements alphabetically and ascending. However, numbers will not be sorted correctly (40 comes before 5). To sort numbers, you must add a function that compare numbers.

    Simply amazing... so a custom sort is required even for an array of integers.

    0 讨论(0)
提交回复
热议问题