Javascript equality operators

前端 未结 1 2029
执笔经年
执笔经年 2021-01-24 13:09

In David Flanagan\'s Javascript guide, there is a statement:

the == operator never attempts to convert its operands to boolean

So he

相关标签:
1条回答
  • 2021-01-24 14:03

    What happens under the hood is

    If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.

    Number(false) == ""
    

    followed by

    If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

    Number(false) == Number("") -> 0 == 0
    

    How can x and y be both true if y is string data type (without conversion)?

    They are not both true, but after type coercion their values are equal.

    the == operator never attempts to convert its operands to boolean

    And that is correct, if you check the comparison algorithm you will find that types are never implicitly casted to Boolean.

    References:

    • 11.9.3 The Abstract Equality Comparison Algorithm
    • 9.3 ToNumber
    0 讨论(0)
提交回复
热议问题