In actionscript, how can you test if an object is defined, i.e., not null?
+2
A:
Just test it against null.
var someObj:Object = getSomeObjectOrMaybeNull();
if(someObj == null) {
trace("someObj is null!");
} else {
trace("someObj is not null!");
}
Herms
2008-11-17 20:50:05
+7
A:
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);
}
Matthew Crumley
2008-11-17 21:06:55
You mean all those if(obj == null || obj == undefined) statements in my codebase can be condensed? woo! :)
Herms
2008-11-18 21:32:41
Could you throw "if (obj)" in there? How does boolean coercion work?
bzlm
2009-02-22 11:03:37
+3
A:
For AS3, 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) trace("c"); // will trace
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.
bzlm
2009-02-22 11:51:13
I thought I would have tried that, but this indeed works, and I think it looks nice too.
Matt Shanley
2009-02-26 01:49:07
I like it too, it makes the code more readable and makes refactoring easier.
bzlm
2009-02-26 07:34:35