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

后端 未结 3 1406
别跟我提以往
别跟我提以往 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: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

提交回复
热议问题