开发者

What passes as true (or false) in an if statement for a variable

开发者 https://www.devze.com 2023-03-16 02:50 出处:网络
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

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 is null; true otherwise

String

false if the value is null or the empty string ""; true otherwise

Number, int, or uint

false if the value is NaN or 0; 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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号