JavaScript type casting

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

    The == operator when one of the operands if Boolean, type-converts the other to Number.

    [] == 0;
    

    Is equivalent to:

    0 == 0;
    

    You can see the complete details of The Abstract Equality Comparison Algorithm on the specification.

    As you can see, an empty array object, when converted to Number, produces 0:

    +[]; // 0
    Number(0);
    

    This is really because its toString method produces an empty string, for example:

    [].toString(); // ""
    
    +""; // 0
    Number(""); // 0
    

提交回复
热议问题