Test if an object is defined in ActionScript

瘦欲@ 提交于 2019-12-20 16:22:44

问题


In ActionScript, how can you test if an object is defined, that is, not null?


回答1:


test if an object is defined

This works in AS2 and AS3, and is the most reliable way to test if an object has a value.

if (obj != null) {
    doSomethingWith(obj);
}

Its also the most reliable way to test an object's property and read it in the same expression:

if (arr[0] != null && arr[0]>5) {
    doSomethingWith(arr[0]);
}

test if an object is null

There's a difference between null and undefined, but if you don't care you can just do a normal comparison between either one because they compare equal:

if (obj == null) {
    doSomethingWith(obj);
}

is the same as

if (obj == undefined) {
    doSomethingWith(obj);
}

If you care about the difference, use the === or !== operator, which won't convert them.

if (obj === undefined) {
    // obj was never assigned a value
}
else if (obj === null) {
    // obj was explicitly set to null
}
else {
    doSomethingWith(obj);
}



回答2:


For ActionScript 3.0, if all you want is a generic test for nothingness, then it's very easy:

var a;
var b;
var c;
var d;
a = undefined;
b = null;
c = 5;
if (a) 
    trace(a);
if (b) 
    trace(b);
if (c) // Will trace
    trace(c); 
if (d) 
    trace(d);

In the example above, only c will trace. This is usually what I need, and just checking if (obj) is the most readable version.

This method uses implicit conversion to a boolean value, also known as boolean coercion, and the details of what values will coerce to false and what values will coerce to true follow ECMA standards and are also documented specifically for ActionScript.




回答3:


Just test it against null.

var someObj:Object = getSomeObjectOrMaybeNull();
if(someObj == null) {
  trace("someObj is null!");
} else {
  trace("someObj is not null!");
}



回答4:


You could also loop through a parent object to see if it contains any instances of the object you're looking for.

foundit=false;
for (var i in this) {
    if (this[i]._name == "MyMovie") {
         foundit=true;
    }
}


来源:https://stackoverflow.com/questions/296861/test-if-an-object-is-defined-in-actionscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!