Bla*_*int 2 actionscript-3 conditional-statements
我见过条件语句,其中条件只是一个变量,而不是布尔变量。该变量是针对一个对象的。
if (myVariable) {
doThis();
}
Run Code Online (Sandbox Code Playgroud)
它似乎正在检查 myVariable 是否为空。这就是它所做的一切吗?这是好的编程习惯吗?这样做不是更好吗?
if (myVariable != null) {
doThis();
}
Run Code Online (Sandbox Code Playgroud)
这样看来就清楚多了。
要正确回答您的问题:
对这样的对象使用 if 语句将检查该对象是否存在。
因此,如果 object 是null
or ,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
Run Code Online (Sandbox Code Playgroud)