【发布时间】:2016-11-24 16:26:09
【问题描述】:
例如,javascript中字符串比较背后的算法是什么
'bc' > 'ac' = true/false ?
'ac' > 'bc' = true/false ?
【问题讨论】:
-
字符串按字母顺序进行比较。
b大于a等。 -
é 和 e 呢?
标签: javascript
例如,javascript中字符串比较背后的算法是什么
'bc' > 'ac' = true/false ?
'ac' > 'bc' = true/false ?
【问题讨论】:
b 大于 a 等。
标签: javascript
字符串是逐个字符比较的,所以第一个字母是最重要的,因此
'bc' > 'ac' = true/false ? => true
'ac' > 'bc' = true/false ? => false
如果第一个字母相等,则比较第二个字母,依此类推,直到其中一个大于或小于或等于。
【讨论】:
JavaScript 按 Unicode codepoints 的顺序比较字符串,并按字典顺序比较 UTF-16 代码单元。
根据您的问题:
'bc' > 'ac' // Because 'b' comes after 'a'.
【讨论】:
这是使用 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.
【讨论】:
不仅在javascript中,简单来说,所有的字符串比较算法都会遵循字典顺序或字典顺序,这意味着它会逐个字符检查每个字符,如果有些不匹配,你可以决定结果
True:
ant < any
aaa < aab
aab < b
b < baa
【讨论】: