JavaScript type casting

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

    From http://forums.whirlpool.net.au/archive/966449:

    a == false:

    In this case, the type of the left-hand side is object, the type of the right-hand side is boolean. Javascript first converts the boolean to a number, yielding 0. Then it converts the object to a "primitive", yielding the empty string. Next it compares the empty string to 0. The empty string is converted to a number, yielding 0, which is numerically equal to the 0 on the right-hand side, so the result of the entire expression is true.

    See §11.9.3 of the ECMAScript spec for all the gory details.

    (!a):

    In this case Javascript converts the object to the boolean true, then inverts it, resulting in false.

提交回复
热议问题