Web前端开发QQ群 110939958-业余程序员

双等号的比较原理

直接摘自ECMA262

章节号:11.9.3 The Abstract Equality Comparison Algorithm

比较 x == y, 当 x 和 y 都是值的时候, 产生truefalse. 这样的一个比较执行如下:

  1. If Type(x) is the same as Type(y), then
    1. If Type(x) is undefined, return true.
    2. If Type(x) is Null, return true.
    3. If Type(x) is Number, then
      1. If x is NaN, return false.
      2. If y is NaN, return false.
      3. If x is the same Number value as y, return true.
      4. If x is +0 and y is −0, return true.
      5. If x is −0 and y is +0, return true.
      6. Return false.
    4. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions). Otherwise, return false.
    5. If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false.
    6. Return true if x and y refer to the same object. Otherwise, return false.
  2. If x is null and y is undefined, return true.
  3. If x is undefined and y is null, return true.
  4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
  5. If Type(x) is String and Type(y) is Number,
    return the result of the comparison ToNumber(x) == y.
  6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
  7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
  8. If Type(x) is either String or Number and Type(y) is Object,
    return the result of the comparison x == ToPrimitive(y).
  9. If Type(x) is Object and Type(y) is either String or Number,
    return the result of the comparison ToPrimitive(x) == y.
  10. Return false.

NOTE 1 鉴于以上相等的定义:
• 可以这样强制字符串比较: "" + a == "" + b.
• 可以这样强制数字比较: +a == +b.
• 可以这样强制布尔值比较:!a == !b.
NOTE 2 双等比较保持以下的不变式:
•  A != B 等价于 !(A == B).
•  A == B 等价于 B == A, 除了A和B求值的顺序不同
NOTE 3 The equality operator is not always transitive. For example, there might be two distinct String objects, each
representing the same String value; each String object would be considered equal to the String value by the == operator,
but the two String objects would not be equal to each other.
NOTE 4 Comparison of Strings uses a simple equality test 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 Strings 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.

最近这部分待译

1个评论 to “双等号的比较原理”

留下评论:

昵称(必须):
邮箱地址 (不会被公开) (必须):
站点
验证码:
评论 (必须)
XHTML: 您可以使用这些标记: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>