[英]Array.sort() compare function
The code I found to sort a list of numbers by ascending order is:我发现按升序对数字列表进行排序的代码是:
arr.sort((a,b) => a-b);
I don't understand how the compare function works.我不明白比较函数是如何工作的。 What if you do arr.sort((a,b) => a+b)?如果你做 arr.sort((a,b) => a+b) 呢?
The sort function uses the sign of the value returned by the comparator : sort 函数使用比较器返回的值的符号:
So a - b
is just a neat shorthand which fulfills those cases.所以a - b
只是一个简洁的简写,可以满足这些情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.