使用.sort((a,b)=> a&b; b)对数组进行排序是可行的.为什么? [英] Sorting an array with .sort((a,b) => a>b) works. Why?

查看:93
本文介绍了使用.sort((a,b)=> a&b; b)对数组进行排序是可行的.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[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.为什么上面的代码正确(如果正确)?

Why? I have some code that uses the above comparison function. A comparison function for numbers should be something like (a,b) => a-b. Why the above code is correct, if it is?

推荐答案

有时会起作用-取决于您的浏览器和输入数组-因为sort期望返回正数,0或负数.表达式 a> b a< b 返回一个布尔值,该布尔值将转换为0或1.0表示相等,因此这是浏览器的特定实现-它如何处理这些相等的值-您正在使用它.

It works sometimes - depending on your browser and the input array - because sort expects either a positive number, 0 or a negative number as return value. The expression a>bor a<b returns a boolean which is converted to 0 or 1. 0 means it's equal, so this is where the specific implementation of the browser - how it handles those equal values - you are using comes into play.

https://www.w3schools.com/jsref/jsref_sort.asp

您还可以通过阅读 ECMAScript规范(这是Javascript所基于的):

You can also tell equal values are not stable by reading the ECMAScript-spec (that's what Javascript is based on):

排序不一定是稳定的(也就是说,比较相等的元素不一定是稳定的)必须保持其原始顺序).[...]如果comparefn不是未定义的,并且不是该数组元素的一致比较函数(请参见下文),则排序顺序是实现定义的.

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.

这篇关于使用.sort((a,b)=&gt; a&b; b)对数组进行排序是可行的.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆