Misunderstanding JavaScript type system
var foo=[0];
if(foo) alert('first');
if(foo==true) alert('second');
Tell me please, why the second ale开发者_运维技巧rt doesn't work? In first alert foo
casts to Boolean
, so
Boolean(foo);
//true
If "foo" is "true", why doesn't the second alert work?
Here,
if( foo) alerts because foo isn't null and the condition evaluates to true.
However, this doesn't mean that foo itself is equal to true, hence the second alert doesn't show.
Because initially foo
is an Array
, not a Boolean
and you are comparing foo
to a boolean value. The if (...)
-statement evaluates to true or false and foo == true
evaluates to false here. If you used if (!!foo == true)
(or just if (!!foo)
) or if (foo != null)
or if (foo)
the second alert would have fired.
Because there's a difference between the conversion of foo
to boolean (which works for an Array) and the comparison of foo
to true
.
In the latter case, it's a comparison without a conversion, and foo
clearly is not the same as true
. Note that a conversion does still take place: foo == true
is false
which is finally "converted" to false
for the if
. :)
精彩评论