Why do alert(!!“0”) and alert(false == “0”) both output true in JavaScript

后端 未结 3 1293
别跟我提以往
别跟我提以往 2020-12-06 11:52

As far as I know in JavaScript !! is supposed to normalize a boolean value converting it to true or false from some other type. This would mean that the \"0\" converts to bo

相关标签:
3条回答
  • 2020-12-06 12:07

    For the first expression, section 9.2 of ECMA-262 defines an abstract operation ToBoolean internally used by the logical NOT operator. It says:

    String
    The result is false if the argument is the empty String (its length is zero); otherwise the result is true.

    For the second expression, JavaScript will perform type coercion when it attempts to compare these values of different data types. Douglas Crockford says that this is a misfeature. It would be false if you had used === instead of ==. The rules are rather complex, so you should directly look in section 11.9.3 of ECMA-262 for the details.

    0 讨论(0)
  • 2020-12-06 12:10

    In the first case, a non-empty string is equivalent to true.

    In the second case, because one operand is a boolean, both operands are converted to numeric values. I believe false converts to the numeric value 0 and the string "0" also converts to a numeric 0, resulting in 0 == 0 which is true.

    Check out the Mozilla reference for operator behavior.

    0 讨论(0)
  • 2020-12-06 12:28

    The == operator checks for loose equality, which has nothing to do with truthiness.

    Specifically, it will convert to operands to numbers, then compare the numbers.
    Strings containing numbers convert to the numbers that they contain; booleans convert to 0 and 1.
    Objects are converted by calling valueOf, if defined.

    Thus, all of the following are true:

    • "1" == 1
    • "0" == false
    • "1" == true
    • "2" != true
    • "2" != false
    • ({ valueOf:function() { return 2; } }) == 2
    • ({ valueOf:function() { return 1; } }) == true
    0 讨论(0)
提交回复
热议问题