JavaScript type casting

后端 未结 5 510
无人及你
无人及你 2020-12-03 16:18

Consider empty JavaScript array:

var a = [];
alert(a == false); // shows true
alert(!a); // shows false!

How to explain this? What are the

5条回答
  •  孤城傲影
    2020-12-03 16:41

    The ! operator checks whether its operand is "falsy".

    The following are true:

    • !false
    • !0
    • !null
    • !NaN
    • !undefined
    • !""

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

    Specifically, a == b 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

提交回复
热议问题