javascript - 使用 .sort((a,b) => a>b) 对数组进行排序是有效的。为什么?

标签 javascript arrays sorting

[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>ba<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/

相关文章:

javascript - Redux 与传统 MVC

javascript - 将 js 代码转换为 jQueryMobile 时出错

javascript - 如何定位包含JQuery中所有子元素的div id

C编程二维数组内存布局

php - 使用匿名函数按两个对象属性对数组进行排序

Excel 排序顺序 - 特殊字符不排在前面

javascript - Leaflet:检索 KML 多边形的边界

javascript - 对于来自 Node.js 数组的每个请求

javascript - 来自 localStorage 问题的 JSON.parse()

java - 如何在 Java 中对 MongoDB 查询结果进行排序?