通过使用“小于/大于"对字符串进行排序比较器中的比较运算符 [英] Sort strings by using "less/greater than" comparison operators in comparator
问题描述
今天,我发现字符串排序的实现对我来说很奇怪:
Today I found a strange for me implementation of strings sorting:
['Data', 'Chata', 'Clata'].sort(function(a, b) { return a > b});
使用这种方法,我们将有效的排序数组作为输出-["Chata", "Clata", "Data"]
.
但是我不清楚它为什么起作用...
Using this approach we take a valid sorted array as the output - ["Chata", "Clata", "Data"]
.
But I don't clearly understand why it works...
我知道比较器函数期望三个不同的输出-零,大于零的整数,小于零的整数.但是在这种情况下,我们只能采用两个值- true (如果大于b)或 false (如果小于b)(强制类型后为1或0)
I know that comparator function expects three different outputs - zero, integer above zero, integer below zero. But in this case we can take only two values - true (if a greater than b) or false (if a less than b) (1 or 0 after type coercion).
有人可以向我解释为什么它起作用吗?
Can anybody explain me why it works?
推荐答案
我不太确定它是如何工作的.
I'm not entirely sure how it manages to work.
编辑,实际上不是.
我使用1000个数字进行了测试( https://jsfiddle.net/alnitak/80cje6gt/),并且单个比较器无法产生正确的排序顺序:
I produced a test using 1000 numbers (https://jsfiddle.net/alnitak/80cje6gt/) and the single comparator doesn't produce the correct sort order:
var m = 0;
a.sort(function(a, b) { ++m; return a > b} );
var n = 0;
b.sort(function(a, b) { ++n; return a < b ? -1 : a > b ? 1 : 0});
这篇关于通过使用“小于/大于"对字符串进行排序比较器中的比较运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!