Actionscript 3 AS3:以非布尔变量作为条件的条件语句

Actionscript 3 AS3:以非布尔变量作为条件的条件语句,actionscript-3,conditional-statements,Actionscript 3,Conditional Statements,我见过条件语句,其中条件只是一个变量,而不是布尔变量。该变量用于对象 if (myVariable) { doThis(); } 它似乎在检查myVariable是否为null。这就是它所做的一切吗?这是好的编程实践吗?这样做不是更好吗 if (myVariable != null) { doThis(); } 这样看来更清楚了 if (myVariable) // fine but not really explicit. 我通常使用: if (myVariable !== nu

我见过条件语句,其中条件只是一个变量,而不是布尔变量。该变量用于对象

if (myVariable) {
  doThis();
}
它似乎在检查myVariable是否为null。这就是它所做的一切吗?这是好的编程实践吗?这样做不是更好吗

if (myVariable != null) {
  doThis();
}
这样看来更清楚了

if (myVariable) // fine but not really explicit.
我通常使用:

if (myVariable !== null) // more readable to me

要正确回答您的问题:

对这样的对象使用if语句将检查对象是否存在

因此,如果对象为
null
undefined
,它将计算为
false
的等价物,否则它将计算为
true

就“良好编程实践”而言,这是非常基于意见的,最好不要使用StackOverflow

没有性能影响,并且您会发现它在基于ECMAScript的语言(如AS3和JS)中非常常见-但是,许多更严格的语言(如C#)需要显式的布尔检查,因此如果您使用多种语言编程,您可能会发现更容易保持一致性

这完全取决于你

以下是一些您可能需要考虑的其他示例:

var str:String;
if(str) //will evaluate as false as str is null/undefined

if(str = "myValue") //will evaluate true, as it will use the new assigned value of the var and you're allowed to assign values inside an if condition (though it's ugly and typically uneccessary)

var num:Number;

if(num) //will evaluate as false

num = 1;
if(num) //will evaluate as true

num = 0;
if(num) //will evaluate as false since num is 0

num = -1;
if(num) //will evaluate as true

var obj:Object
if(obj) //will evaluate false

obj = {};
if(obj) //will evaluate true (even though the object is empty, it exists)

var func:Function;
if(func) //false

func = function(){};
if(func) //true - the function exists

function foo():Boolean { return false; }
if(foo) //true - the function exists

if(foo()) //false, the return of the function is false

function foo1():void { return; };
if(foo1()) //false as there is no return type

如果它更具可读性,那么我假设您也对布尔值执行此操作:如果(myboolean==true),如果不是,那么它的可读性就不会降低或提高。无论哪种方式,它都是完全好的,除非函数必须显式检查该类型的对象是否为null If(myfunction!=null)@BotMaster—如果使用函数执行此操作,您只会收到一条编译器警告(因为编译器会认为您无意中遗漏了()),它仍然可以编译并工作。但在我看来,明确地检查函数肯定更具可读性。我不知道为什么会投反对票。。。这可能是许多程序员想当然的事情,但这是一个有效的问题无论你选择什么,在编程中一致性总是首选的。所以,如果您像这样计算布尔值,如果(myboolean==true),那么您也可以对所有内容进行计算。如果你不这样做,那么你也可以对任何可以用这种方式评估的东西做同样的事情。布尔值和默认类型的复杂对象(null)都是在if条件中计算的,因此以一种方式计算一个复杂对象和以另一种方式计算另一个复杂对象是不一致的。第二种if是赋值,将生成编译器警告。@botMaster。但是有些人喜欢在if语句中使用赋值,所以我把它包括在内。