Search code examples
javascripte4x

e4x: how to best check existence of an attribute?


I know I can do it with the length() method:

>x = <a attr1='33' />
>x.@attr1
33
>x.@attr1.length()
1
>x.@attr2.length()
0

so I could use

if (x.@someattr.length() > 0)
{
    .... do something ....
}

but is there a more appropriate way?


Solution

  • Never mind, I found the answer by poring through the Ecma-357 standard, particularly the XML.prototype.* and XMLList.prototype.* sections 13.4 and 13.5.

    It's the hasOwnProperty() method:

    js>x = <a attr1='33' ><item>gumball!</item></a>
    <a attr1="33">
      <item>gumball!</item>
    </a>
    js>x.@attr1
    33
    js>x.hasOwnProperty('@attr1');
    true
    js>x.hasOwnProperty('@attr2');
    false
    js>x.hasOwnProperty('item');
    true
    js>x.hasOwnProperty('mongoose');
    false