actionscript-3 - AS3 : Conditional statement with a non-boolean variable as the condition

标签 actionscript-3 conditional-statements

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

if (myVariable) {
  doThis();
}

它似乎正在检查 myVariable 是否为空。这就是它所做的一切吗?这是好的编程习惯吗?这样做不是更好吗?

if (myVariable != null) {
  doThis();
}

这样看起来就清楚多了。

最佳答案

正确回答您的问题:

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

因此,如果对象为 nullundefined ,则其计算结果将等于 false,否则它将等于 true .

就“良好的编程实践”而言,这是非常基于观点的,最好不要在 StackOverflow 中出现。

不会对性能造成影响,您会发现它在基于 ECMAScript 的语言(例如 AS3 和 JS)中非常常见 - 然而,许多更严格的语言(例如 C#)需要显式 bool 检查,因此如果您使用多种语言进行编程,可能会发现更容易保持一致。

这完全取决于你!

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

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

关于actionscript-3 - AS3 : Conditional statement with a non-boolean variable as the condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25899157/

相关文章:

lisp - lisp有什么不同

python - 具有开始和结束条件的序列的长度(计数)Python

actionscript-3 - '[Inspectable]' 元数据标签

flash - 带有公共(public) getter 的内部 setter 不起作用

R:基于多个条件的两个数据帧的子集

c++ - 在循环的停止条件下访问数组值是否安全?

c# - 使用 Eval Boolean 为 asp.net 控件设置样式

css - 绑定(bind) MXML CSS 值

actionscript-3 - 弹性 : Access static constant from parent

flash - 使用ActionScript 3录制保存声音到文件,而不是通过麦克风