gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:10:45 25 4
gpt4 key购买 nike

[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。为什么上面的代码是正确的,如果是的话?

最佳答案

它有时会起作用 - 取决于您的浏览器和输入数组 - 因为排序需要正数、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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com