为什么Array.prototype.sort在Chrome中有不同的行为? [英] Why Array.prototype.sort has different behavior in Chrome?
问题描述
我正在尝试对数组进行排序,因此 Chrome V79 中的行为与 Firefox Dev Edition V72 (均为台式机版本)不同.
I was trying to sort an Array And i got this different behavior in Chrome V79 than Firefox Dev Edition V72 (both in Desktop version).
这是测试,
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中,我得到了这个结果,
但是,是的,它对数组进行排序并重写变量,但返回数组的未排序版本.因此,当我不带任何变量而直接传递Array时,我没有排序.但是,
But Yeah it sorts the Array and REWRITES THE VARIABLE but returns the unsorted version of the Array. So, When I am passing The Array directly without any var, i get no sorting. But,
注意:在示例图中,有两个示例我正在练习
call
func.忘了删除它.因此,只需忽略它.他们两个都是一样的.
Note: In the Example Imgs, there are two exmaple's I was practicing
call
func. And forgot to remove it. So, just ignore it. Both of 'em are same.
推荐答案
注释中指出,您提供的用于排序的函数应返回:
As pointed out in the comments, the function you provide for sorting should return:
- 如果
a
大于b
,则为正数 - 如果
b
大于a
,则为负数 - 如果相等则为0
因此,您可以返回的简单表达式是 a-b
而不是 a>b
(如果您要升序排序):
Therefore, a simple expression you could return is a - b
instead of a > b
(if you want to sort ascendingly):
console.log([4, 2, 5, 1, 3].sort((a, b) => a-b));
这篇关于为什么Array.prototype.sort在Chrome中有不同的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!