【问题标题】:How does string comparison work in JavaScript? [duplicate]字符串比较在 JavaScript 中是如何工作的? [复制]
【发布时间】:2016-11-24 16:26:09
【问题描述】:

例如,javascript中字符串比较背后的算法是什么

'bc' > 'ac' = true/false ?
'ac' > 'bc' = true/false ?

【问题讨论】:

标签: javascript


【解决方案1】:

字符串是逐个字符比较的,所以第一个字母是最重要的,因此

'bc' > 'ac' = true/false ? => true
'ac' > 'bc' = true/false ? => false

如果第一个字母相等,则比较第二个字母,依此类推,直到其中一个大于或小于或等于。

【讨论】:

    【解决方案2】:

    JavaScript 按 Unicode codepoints 的顺序比较字符串,并按字典顺序比较 UTF-16 代码单元。

    根据您的问题:

    'bc' > 'ac' // Because 'b' comes after 'a'.
    

    【讨论】:

      【解决方案3】:

      这是使用 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.
      

      【讨论】:

        【解决方案4】:

        不仅在javascript中,简单来说,所有的字符串比较算法都会遵循字典顺序或字典顺序,这意味着它会逐个字符检查每个字符,如果有些不匹配,你可以决定结果

        True: 
        ant < any
        aaa < aab 
        aab < b 
        b < baa
        

        【讨论】:

          猜你喜欢
          • 2023-03-03
          • 2012-11-04
          • 2017-12-24
          • 1970-01-01
          • 2022-11-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-27
          相关资源
          最近更新 更多