问题
[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>b
or 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