javascript的字符串大小比较

javascript的字符串大小比较是按照字符串中对应的字符在编码表(UTF-16)中的数值的大小来进行比较的,比如'abcd''abaa'进行比较,先比较第一个字符,发现他们都是a大小一样,然后就会比较第二个发现都是b,然后比较第三个字符c的编码大于a,比较出了大小,所以字符串abcd大于字符串abaa。字符串的前缀不会大于自己,'abcdefe' > 'abc'结果为true
对中文的比较也是同样的规则,比如你好你们进行比较也是比较字符在编码表中的数值大小进行的,如下'你好' > '你们'。首先比较第一个字符,发现'你'大小相同,因为'你'.charCodeAt(0)等于你'.charCodeAt(0)'等于20320,然后比较第二个字符'好''们''好'的编码值为22909,'们'的编码值为20204,所以'好'大于'们'。所以最后'你好'是大于'你们'

'好'.charCodeAt(0)  -> 22909
'们'.charCodeAt(0)  -> 20204
  1. Else, both px and py are Strings
    1. If py is a prefix of px, return false. (A String value p is a prefix of String value q if q can be the result of concatenating p and some other String r. Note that any String is a prefix of itself, because r may be the empty String.)
    2. If px is a prefix of py, return true.
    3. 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.)
    4. Let m be the integer that is the code unit value for the character at position k within px.
    5. Let n be the integer that is the code unit value for the character at position k within py.
    6. If m < n, return true. Otherwise, return false.

NOTE 1Step 3 differs from step 7 in the algorithm for the addition operator + (11.6.1) in using and instead of or.
NOTE 2The comparison of Strings uses a simple lexicographic ordering on sequences of code unit values. There is no attempt to use the more complex, semantically oriented definitions of character or string equality and collating order defined in the Unicode specification. Therefore String values that are canonically equal according to the Unicode standard could test as unequal. In effect this algorithm assumes that both Strings are already in normalised form. Also, note that for strings containing supplementary characters, lexicographic ordering on sequences of UTF-16 code unit values differs from that on sequences of code point values.

参考

http://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5
小议 js 下字符串比较大小

转载于:https://www.cnblogs.com/ZiYangZhou/p/8407346.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值