This question already has answers here:
Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?

(2个答案)


在11个月前关闭。




我正在尝试对数组进行排序,但在Chrome V79中,我的行为不同于Firefox Dev Edition V72(均在桌面版本中)。

这是测试
console.log([4, 2, 5, 1, 3].sort((a, b) => a>b));
console.log(Array.prototype.sort.call([4, 2, 5, 1, 3], (a, b) => a>b));

在Firefox Dev中,我得到了这个结果,

javascript - 为什么Array.prototype.sort在Chrome中有不同的行为?-LMLPHP

但是在Chrome中,为什么我得到这个结果,

javascript - 为什么Array.prototype.sort在Chrome中有不同的行为?-LMLPHP

但是当我用var传递相同的数组时,我得到了,

javascript - 为什么Array.prototype.sort在Chrome中有不同的行为?-LMLPHP

但是,是的,它对数组进行排序并重写变量,但返回数组的未排序版本。因此,当我不带任何变量而直接传递Array时,我没有排序。但,

根据MDN's reference page应该不返回排序后的数组??

为什么有区别?

最佳答案

如注释中所指出,您提供的用于排序的函数应返回:

  • 如果a大于b,则为正数
  • 如果b大于a,则为负数
  • 如果它们等于
  • ,则为0

    因此,您可以返回的一个简单表达式是a - b而不是a > b(如果要升序排序):

    console.log([4, 2, 5, 1, 3].sort((a, b) => a-b));

    关于javascript - 为什么Array.prototype.sort在Chrome中有不同的行为? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59773396/

    10-12 15:39