What passes as true (or false) in an if statement for a variable
In this code, what values of myVar
will behave as true
and false
?
if(myVar){}
In JavaScript for example, the following val开发者_开发知识库ues are falsy
null
undefined
0
''
false
Object
false
if the instance isnull
;true
otherwise
String
false
if the value isnull
or the empty string""
;true
otherwise
Number, int, or uint
false
if the value isNaN
or0
;true
otherwise
null
false
From here.
If (myVar)
is a bool, then it'll obvious pass if it's true, and fail if not. If the bool was never initialized (like var myBool:Boolean;
instead of var myBool:Boolean = true
) then it's false by default. This same concept applies to builtin objects like Number, int etc. Pretty much for everything else, it will only pass as true if the object has been initialized through the object constructor or through a direct assignment, like so:
var a:MovieClip = new MovieClip();
var b:MovieClip = a;
精彩评论