Why does points.sort(function(a, b){return a-b}); return -1, 0 or 1?

前端 未结 6 1715
滥情空心
滥情空心 2020-12-08 23:47

My difficulty here could be my mathematical illiteracy, but I was trying to sort some numbers in a JavaScript array and this is the solution I found online. It does indeed w

6条回答
  •  一个人的身影
    2020-12-09 00:41

    It is not bound to be -1, 0, 1 any negative or positive number will do the trick.

    But how it works? The sort() method needs to know the relation between each two elements in order to sort them. For each pair (according to the algorithm used) it calls the function then based on the return value, may swap them. Note that a-b returns a negative value if b>a and a positive one if a>b. That leads to an ascending order.

    Just for test, replace a-b with b-a and you will get a descending order. You may even make it more complicated, sort them based on (for example) their least significant digit:

    a.sort(function() {return (a%10) - (b%10);}
    

提交回复
热议问题