Wrong sort callback - results still correct

橙三吉。 提交于 2020-01-15 12:39:07

问题


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

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