Algorithm of JavaScript “sort()” Function

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

    The problem lies with the use of strings to represent numbers, which the sort function unfortunately does as default. Strings are sorted alphabetically. The comparison function in your code just forces the strings to be evaluated as numbers.

    I'd consider it very bad API design that the sort function defaults to treating the elements as strings, but it may be necessary given JavaScript's loose type system..

提交回复
热议问题