Algorithm of JavaScript “sort()” Function

前端 未结 8 797
灰色年华
灰色年华 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:16

    The function sort will sort your array in an alphabetical sort order, even if it consists of integers; that's the reason why your array is sorted like that by calling sort without a parameter.

    sortOrder is a comparison function that is used to define a new sort order for the array; this function will return

    • 0, if a and b are of the same value
    • a value > 0, if a has a bigger value than b
    • a value < 0, if a has a smaller value than b

    In JavaScript, "1" - "2" will return -1, which is a number, and not a string anymore; by using the comparison function sortOrder on your array consisting of numbers wrapped in strings, you're ordering the array in a numerical sort order, thus resulting in 1,5,10,25,40,100, and not in 1,10,100,25,40,5

提交回复
热议问题