First of all, please forgive me for doing a title party;
But I think from the discovery of the problem to the final solution of the process is quite interesting, I hereby record;
Background
Developed in the last two days 航班延误宝 is the H5 page embedded in the client (Android, iOS) WebView. Some of the content needs to be sorted before being displayed. The code is simple:
let m = [6,4,8,10,3,5] console.log(‘排序前:‘, [6,4,8,10,3,5]) m.sort((a, b) => a < b) console.log(‘排序后:‘, m)
PS: Did you find the problem with this piece of code? If you know the reason, in order to save your precious time, after the content will not look;
The content printed in the PC browser is as follows:
排序前: (6) [6, 4, 8, 10, 3, 5]排序后: (6) [10, 8, 6, 5, 4, 3]
But I tested it with my iPhone (only the iOS browser, the iOS Flight Butler client), but I had a different experience:
wtf! The result is the same as no order, why?
Solve
The initial speculation may be that there is a sort compatibility problem. As sort a result, the test is performed with an insert sort substitution, and the results are normal.
Later, in Zhang (Zhen) (DA) Division (TUI) under the guidance of understanding sort the implementation of the norms, only to understand that the original is the implementation of the problem .
Where is the problem?
There is one in the sort implementation specification: if Comparefn (A, b) = = = 0, there is a = = = b and b = = = a .
At this point we see var comparefn = (a, b) => a < b that it is equal to var comparefn = (a, b) => a < b ? 1 : 0 .
It has a hidden vulnerability: when a >= b , comparefn(a,b) === 0 . According to the norm, by comparefn(a,b) === 0 inference a === b , it is clear that there are contradictions.
So, I wrote this comparefn was wrong , holyshit!.
Then the correct wording should be: var comparefn = (a, b) => b - a .
The end of the sprinkle flowers;
Ask again: Why does Android and iOS behave differently? The two families should be different in their implementation.
More:
Array.prototype.sort Implementation Specification
[Bug] JS sort function is not valid in iOS