问题
As generally known, sort() callback function is supposed to return -1, 0 or 1, depending on how its arguments compare. Despite this, I often see sort callbacks written in the following way:
someArray.sort(function(a, b) { return a > b })
Although this obviously doesn't conform the specs, since the callback only returns 0 or 1, it still seems to produce correct results:
a = []
for(i = 0; i < 1000; i++)
a.push(Math.floor(Math.random() * 1000))
console.log(a.sort(function(a, b) { return a > b }))
Can anyone provide an example where the above callback function will cause an array to be sorted incorrectly? Array elements don't have to be numbers.
回答1:
It all depends on the specific browser's sorting implementation, whether it uses the less-than comparison, and whether it autocasts sorting function's return value to int.
This fails in IE9, but works in Chrome:
"cadbe".split('').sort(function(a,b) { return a > b });
This works in IE9 and Chrome:
"cadbe".split('').sort();
来源:https://stackoverflow.com/questions/9375788/wrong-sort-callback-results-still-correct