简体   繁体   English

通过在比较器中使用“less / greater than”比较运算符对字符串进行排序

[英]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.

相关问题 在循环中使用变量作为大于/小于运算符 - Using variables as greater than / less than operators in a loop 小于和大于运算符不工作 - Less than and greater than operators not working 为什么 JavaScript 没有严格的大于/小于比较运算符? - Why doesn't JavaScript have strict greater/less than comparison operators? 严格的价值比较(小于/大于) - Strict Value Comparison (less/greater than) 如何使用javascript比较两个日期时间与时区偏移(比较大于或小于) - How to compare two datetimes with time zone offset using javascript (comparison greater than or less than) Javascript开关大于/小于运算符不起作用 - Javascript switch greater than / less than operators not working arrays 上“大于”(和另一个不等式比较运算符)的行为 - Behavior of “Greater than” (and another inequality comparison operators) on arrays 我如何分类考虑大于和小于考虑? - How do I sort taking greater than and less than into consideration? 数组如何与关系运算符(如小于和大于?)进行交互? - How do arrays interact with relational operators like less-than and greater-than? 查询集合中使用小于或大于语句的位置吗? - Query Collection using Where with a less than or greater than statement in it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM