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

前端 未结 2 378
渐次进展
渐次进展 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条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-25 07:37

    It seems to work in all cases for me.

    You have not considered any cases of numbers that consist of multiple digits in string representation. The lexicographic default comparison also fails on negative numbers.

    See How to sort an array of integers correctly for more information and some counterexamples.

提交回复
热议问题