简体   繁体   中英

Firefox Array.prototype.sort - is this behaviour correct?

I noticed a strange sorting behaviour in Firefox. Running the following code on the console:

[1,2,3].sort ( (a,b) => 1 )

On Chrome / Chromium (on linux and Windows) I get [1,2,3]

On Edge I get [1,2,3]

On FireFox (on Linux and Windows) I get [3,2,1]

Is this incorrect behaviour for Firefox?

Your sort comparator function does not obey the requirements of such a function, so the behavior is undefined. A comparator function must consistently return the same "conclusion" value for any pair of elements, regardless of the order the elements are passed as parameters. Your function indicates to the internal sort algorithm that (for example) 1 should appear after 2, but also that 2 should appear after 1. Because of that inconsistency, you get erroneous results.

The comparator can do anything it wants, but for any two elements in the array a and b , the result should be

  • -1 (or any negative number) if a should appear before b in the sorted array;
  • 1 (or any positive number) if b should appear before a in the sorted array;
  • 0 if the elements are already in the correct order

That must be true for the two elements regardless of how they are actually passed into the comparator, and it must be consistent no matter how many times the same two elements are compared.

edit — actually the results just need to have the right sign; they don't actually have to be 1 or -1, just a negative value or a positive value. That makes it easier to compare numbers, because a - b gives a proper result (negative, positive, or zero).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM