错误的排序回调-结果仍然正确 [英] Wrong sort callback - results still correct

查看:73
本文介绍了错误的排序回调-结果仍然正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知, sort()回调函数是应该返回-1、0或1,具体取决于参数的比较方式.尽管如此,我经常看到排序回调以下列方式编写:

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 })

尽管这显然不符合规范,但由于回调仅返回0或1,因此它似乎仍会产生正确的结果:

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.

推荐答案

这全都取决于特定浏览器的排序实现,是否使用小于比较以及是否将排序函数的返回值自动转换为int.

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.

此操作在IE9中失败,但在Chrome浏览器中有效:

This fails in IE9, but works in Chrome:

"cadbe".split('').sort(function(a,b) { return a > b });

这在IE9和Chrome中有效:

This works in IE9 and Chrome:

"cadbe".split('').sort();

这篇关于错误的排序回调-结果仍然正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆