Sorting an array with .sort((a,b) => a>b) works. Why?

时间秒杀一切 提交于 2021-01-28 14:09:47

问题


[9,2,1,80].sort((a,b) => a>b)
// gives [ 1, 2, 9, 80 ]

[9,2,1,80].sort((a,b) => a<b)
// gives [ 80, 9, 2, 1 ]

Why? I have some code that uses the above comparison function. A comparison function for numbers should be something like (a,b) => a-b. Why the above code is correct, if it is?


回答1:


It works sometimes - depending on your browser and the input array - because sort expects either a positive number, 0 or a negative number as return value. The expression a>bor a<b returns a boolean which is converted to 0 or 1. 0 means it's equal, so this is where the specific implementation of the browser - how it handles those equal values - you are using comes into play.

https://www.w3schools.com/jsref/jsref_sort.asp

You can also tell equal values are not stable by reading the ECMAScript-spec (that's what Javascript is based on):

The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order). [...] If comparefn is not undefined and is not a consistent comparison function for the elements of this array (see below), the sort order is implementation-defined.




回答2:


The > returns only 0 (equal) or 1 (greater), while sort compare function must return negative, zero or positive.that why the > or < work for some value



来源:https://stackoverflow.com/questions/53837990/sorting-an-array-with-sorta-b-ab-works-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!