运算符<或>比较两个字符串时可以工作吗? [英] How does operator < or > work when comparing two strings?

查看:39
本文介绍了运算符<或>比较两个字符串时可以工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用< 来比较两个这样的字符串:

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):

a.如果 py px 的前缀,则返回false.

b.如果 px 是py的前缀,则返回true.

C. k 为最小的非负整数,以使 px 中的位置 k 处的字符与位置处的字符不同 py 中的k .(必须有这样的 k ,因为两个String都不是另一个的前缀.)

d.假设 m 是整数,它是 px 中位置 k 处字符的代码单位值.

e.假设 n 是整数,它是 py 中位置 k 处字符的代码单位值.

F.如果 m<n ,返回true.否则,返回false.

a. If py is a prefix of px, return false.

b. If px is a prefix of py, return true.

c. Let k be the smallest nonnegative integer such that the character at position k within px is different from the character at position k within py. (There must be such a k, for neither String is a prefix of the other.)

d. Let m be the integer that is the code unit value for the character at position k within px.

e. Let n be the integer that is the code unit value for the character at position k within py.

f. If m < n, return true. Otherwise, return false.

这篇关于运算符&lt;或&gt;比较两个字符串时可以工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆