JavaScript type casting

后端 未结 5 494
无人及你
无人及你 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:42

    When comparing an object to a primitive value via the == operator, the object coerces into an primitive value itself (number or string). In this case [] coerces into 0, then false coerces into 0:

    [] == false
    0 == false
    0 == 0
    

    which is true.

    The ! operator coerces into boolean and then inverts the value. [] into boolean is true (like with any object). Then invert to become false

    ![]
    !true
    false
    

提交回复
热议问题