【问题标题】:String comparison - Javascript字符串比较 - Javascript
【发布时间】:2015-12-23 15:38:25
【问题描述】:

我正试图了解 Javascript 中的字符串比较

function f(str){
  return str[0] < str[str.length -1]
}
f("a+"); // false

ASCII 码:'a' == 97, '+' == 43

我认为我的测试是否正确:f(str) 是基于上面的 ASCII 值?

【问题讨论】:

  • 你已经接近了:在比较两个 Strings 时,重要的是 unicode 值
  • console.log( 'a' &gt; '+' ); // true
  • @ZakariaAcharki - 更深入的了解。
  • 检查this out(相关部分以'Else,px和py都是字符串'开头)。
  • @dan 实际上这正是 97 和 43 :)

标签: javascript


【解决方案1】:

你不需要一个函数或一个复杂的测试来拉开一个字符串。只需执行'a' &lt; '+' 并从所发生的事情中学习。或者,更简单地说,使用 'a'.charCodeAt(0) 检查 char 的 charcode。

【讨论】:

    【解决方案2】:

    你几乎是对的。它基于 unicode 代码单元(不是代码点,这是 16 位编码版本),而不是基于值的 ascii。

    来自ECMAScript 2015 specification

    If both px and py are Strings, then
      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.)
      If px is a prefix of py, return true.
      Let k be the smallest nonnegative integer such that the code unit at index k within px is different from the code unit at index k within py. (There must be such a k, for neither String is a prefix of the other.)
      Let m be the integer that is the code unit value at index k within px.
      Let n be the integer that is the code unit value at index k within py.
      If m < n, return true. Otherwise, return false.
    

    注2

    字符串的比较使用简单的字典顺序 代码单元值的序列。没有尝试使用更多 复杂的、面向语义的字符或字符串定义 Unicode 规范中定义的相等和整理顺序。 因此,根据 Unicode 标准可以测试为不相等。实际上这个算法 假设两个字符串都已经是规范化的形式。另外,请注意 对于包含补充字符的字符串,字典序 UTF-16 代码单元值序列的排序不同于 代码点值序列。

    基本上意味着字符串比较是基于“代码单元”的lexicographical order,它是unicode字符的数值。

    【讨论】:

      【解决方案3】:

      JavaScript 引擎可以使用 UCS-2 或 UTF-16(这在大多数实际用途中是相同的)。

      因此,从技术上讲,您的函数基于 UTF-16 值,并且您正在比较 0x00610x002B

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-04
        • 2017-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-13
        • 1970-01-01
        相关资源
        最近更新 更多