该算法在javascript中的字符串比较背后起作用,例如
'bc' > 'ac' = true/false ?
'ac' > 'bc' = true/false ?
答案 0 :(得分:2)
这是使用ECMA-5中的The Abstract Relational Comparison Algorithm计算的。相关部分引用如下。
4. Else, both px and py are Strings
a) 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.)
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.
答案 1 :(得分:0)
字符串逐字符进行比较,因此第一个字母最重要,因此
'bc' > 'ac' = true/false ? => true
'ac' > 'bc' = true/false ? => false
如果第一个字母相等,那么第二个字母将被比较,依此类推,直到其中一个字母大于或小于或等于。
答案 2 :(得分:0)
javascript会将字母转换为ascii代码并首先比较第一个字符。
您可以在此处查看ascii代码表http://www.kerryr.net/pioneers/ascii2.htm
来自你的问题
'bc' > 'ac' // because b > a
答案 3 :(得分:0)
不仅在javascript中,简单来说,所有字符串比较算法都将遵循字典顺序或字典顺序,这意味着它将逐个字符地检查每个字符,如果有不匹配,则可以决定结果
True:
ant < any
aaa < aab
aab < b
b < baa