[英]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});
Using this approach we take a valid sorted array as the output - ["Chata", "Clata", "Data"]
. 使用这种方法,我们将有效的排序数组作为输出 -
["Chata", "Clata", "Data"]
。 But I don't clearly understand why it works... 但我不清楚它为何有效......
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).
但在这种情况下,我们只能取两个值 - true (如果大于b)或false (如果小于b)(类型强制后为1或0)。
Can anybody explain me why it works? 任何人都可以解释一下它的工作原理吗?
I'm not entirely sure how it manages to work. 我不完全确定它是如何运作的。
EDIT it actually doesn't. 编辑它实际上没有。
I produced a test using 1000 numbers ( https://jsfiddle.net/alnitak/80cje6gt/ ) and the single comparator doesn't produce the correct sort order: 我使用1000个数字( https://jsfiddle.net/alnitak/80cje6gt/ )进行了测试,单个比较器没有产生正确的排序顺序:
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});
When comparing strings, comparison is done letter by letter. 比较字符串时,比较是逐字逐句完成的。 So
c
has lower symbol value than d
( Check this table ) 因此
c
符号值低于d
( 检查此表 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.