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
- 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
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.+
() in using and instead of or.