开发者

Flex 3: How can I see if a variable exists

I'm 开发者_如何学Pythongetting the "Error #1009: Cannot access a property or method of a null object reference." error on my application. Is there a function I can use to detect this before it causes an error... maybe something like:

isValid(variableName);

I know there's one, because i've used it before, but i can't remember what it is right now.

Any help would be greatly appreciated.


My guess: hasOwnProperty


Simply put, a null object maps to a Boolean false. suppose:

var x:ArrayCollection; //uninitialised
if(x) {
    Alert.show("X");
} else {
    Alert.show("NOT X");
}

Above code will show an alert saying NOT X because a null variable maps to false

However, if you want to check whether an object has a property with a particular name, try

var o:MyObject=new MyObject();
if(o.hasOwnProperty("something")) {
    Alert.show(o.something);
} else {
    Alert.show("Something undefined");
}

now if there is a property called "something" on o, EVEN IF ITS VALUE IS null, it will go into if()... otherwise it will go into else.


It's actually quite simple. Use a try/catch construct with the (err:) For example, I use this to surround parsing code that can generate errors. "Error" means any error.

try { relation.parseObject(XMLObject["relation"],source); } 
catch (err:Error) {tr.output(mN + "bad relation " + err)}; 

You would do this:

try {
newvalue = variableName;
}
catch (error:ReferenceError) { <do something> }


A simple if statement will work.

if (myVariable)
{
  //do something
}

UPDATE: After looking at the code that's causing the error, my guess is that either wholeProject[j] is null or wholeProject[j].wholePosition is null. Try something like this:

if (wholeProject[j] && wholeProject[j].wholePosition)
{
  for (var k:int = 0; k < wholeProject[j].wholePosition.length; k++)
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜