expression evaluation with boolean values
In Java or other similar languages I can't do:
a < b > c
where a,b,c are boolean types.
In Javascript I can do that and also with other data types values:
va开发者_开发问答r t = 3;
var z = true;
t > z // will be true
Now why the results is true???
Because Javascript is willing to do type conversions at the drop of a hat. Boolean true
is coerced to numeric 1
.
Note that 1 == true
is true
, but 1 === true
is false
.
True will be converted to 1. And 3 is greater than one...
JavaScript first casts the boolean true
to a number for the comparison. In this case true
is cast to 1
.
Many objects will not be cast to numbers though. For example, {}
is NaN
.
精彩评论