[9,2,1,80].sort((a,b) => a>b)
// gives [ 1, 2, 9, 80 ]
[9,2,1,80].sort((a,b) => a<b)
// gives [ 80, 9, 2, 1 ]
为什么?我有一些使用上述比较函数的代码。数字的比较函数应该类似于 (a,b) => a-b。如果上面的代码是正确的,为什么是正确的?
最佳答案
有时它会起作用 - 取决于您的浏览器和输入数组 - 因为 sort 需要正数、0 或负数作为返回值。表达式a>b
或a<b
返回一个转换为 0 或 1 的 bool 值。0 意味着它相等,因此这就是您正在使用的浏览器的特定实现(它如何处理这些相等值)发挥作用的地方。
https://www.w3schools.com/jsref/jsref_sort.asp
您还可以通过阅读ECMAScript-spec来判断相等的值不稳定。 (这就是 Javascript 的基础):
The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order). [...] If comparefn is not undefined and is not a consistent comparison function for the elements of this array (see below), the sort order is implementation-defined.
关于javascript - 使用 .sort((a,b) => a>b) 对数组进行排序是有效的。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53837990/