我已经看到条件语句,其中条件只是一个变量,它不是一个布尔变量。变量用于对象。
if (myVariable) {
doThis();
}
似乎在检查myVariable是否为null。这就是它的全部吗?这是一个很好的编程实践?这样做会不会更好?
if (myVariable != null) {
doThis();
}
这种方式似乎更加清晰。
答案 0 :(得分:3)
正确回答你的问题:
对这样的对象使用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
答案 1 :(得分:0)
if (myVariable) // fine but not really explicit.
我通常使用:
if (myVariable !== null) // more readable to me