问题描述
我使用<
来比较两个这样的字符串:
I used <
to compare two strings like this:
console.log('ca'<'bb'); //false
我已经知道它会比较字符的Unicode数字.因为 c
不小于 b
.
I already know that it compares Unicode number of the character.Because c
is not less than b
.
但是,当我这样做时:
console.log('ba'<'bb');//true
让我感到困惑,因为 b
不少于 b
本身,似乎只是跳过了它并比较了下一个字符.
Makes me confused, as b
is not less than b
itself, seems it just skipped it and compared the next character.
无论如何,我想知道当使用<
或>
比较两个字符串时,这里的规则是什么,对于某些复杂的情况,如果两个字符串具有不同的长度?
Anyway, I wonder what's the rule here when <
or >
is used to compare two strings, and for some complicated situations what if when the two strings have different lengths?
推荐答案
它完全按照您的建议执行-跳过两个字符串中相同的字符,并按代码单位值比较前几个不同的字符.规范中的抽象关系比较算法对此进行了解释(强调):
It does exactly as you suggested - it skips characters that are the same in both strings and compares the first different characters by code unit value. This is explained by the abstract relational comparison algorithm in the spec (emphasis added):
这篇关于运算符<或>比较两个字符串时可以工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!