Unintuitive E4X Gotcha in Actionscript 3

8th January 2008 @ 1:17 am
nowhere
This is the second in a series of posts about actionscript 3 that I announced earlier, and my last for today. Here's the feed of posts tagged as3.

Testing for the existence of a property on an Object is simple in actionscript 3:

var object:Object = { sub: "sub" };

trace("testing object properties");

if (object.sub) { trace("CORRECT: object has a sub element"); } else { trace("WRONG: object has no sub element"); }

if (object.nosub) { trace("WRONG: object has a nosub element"); } else { trace("CORRECT: object has no nosub element"); }

This yields the correct output:

testing object properties CORRECT: object has a sub element CORRECT: object has no nosub element

However, the same thing isn't as intuitive with XML and E4X:

var xml:XML = sub;

trace("testing xml element");

// don't do this, it will give false positives! if (xml.sub) { trace("CORRECT: xml has a sub element"); } else { trace("WRONG: xml has no sub element"); }

// don't do this, it will give false positives! if (xml.nosub) { trace("WRONG: xml has a nosub element"); } else { trace("CORRECT: xml has no nosub element"); }

This gives incorrect output:

testing xml element CORRECT: xml has a sub element WRONG: xml has a nosub element

The way to test reliably for the existence of xml elements is to check the length() method on the element:

trace("testing xml length()");

// this works to test for the existence of an element if (xml.sub.length()) { trace("CORRECT: xml has a sub element"); } else { trace("WRONG: xml has no sub element"); }

// this also works to test for the non-existence of an element if (xml.nosub.length()) { trace("WRONG: xml has a nosub element"); } else { trace("CORRECT: xml has no nosub element"); }

This yields the correct output:

testing xml length() CORRECT: xml has a sub element CORRECT: xml has no nosub element

Hey, it's boring but true!