开发者

javascript typeof item === "undefined" never returns true

In the following code sample, typeof item === "undefined" never returns true. i am trying to get an attribute from XML, if the attribute is not there in the XML it returns "undefined", but i am not able to capture whether it has returned undefined or not, firebug shows "typeof item" as an "object"

var item;
var itemIDs = {};
if (items.status == 200)
{   
    var rows = items.responseXML.getElementsByTagName('z:row');
    for(i=0;i<rows.length;i++)
    { 
        //rows[i].attr(attribute);
        item = rows[i].getAttribute(attribute);
        if(typeof item === "undefined")
        {
            continue;

        }
        else
        {
            item = item.match(/[^\d+;#][\w\W]+/);
            itemIDs[item] = 1 ;
        }

    }
}
else
{
     alert('There was an error: ' + items.statusText);
}

return itemIDs;

Edit: I changed the condition to if(item == undefined), The code now wor开发者_Python百科ks as expected now

Edit2: Double checked it, item variable was never null , it was "undefined"


getAttribute returns an object (valid object or a null object). So the check (typeof item === "undefined") is not correct. It should be (item === null).


Some browser's implementation of getAttribute may return an empty string if the attribute doesn't exist. You could test for both null and "", or alternatively use hasAttribute.

if(rows[i].hasAttribute(attribute))
{
    // do stuff...
}

https://developer.mozilla.org/en/DOM/element.getAttribute


It's because typeof null === 'object' (contrary to the common sense). You should check if getAttrbiute's return value equals null.

item = rows[i].getAttribute(attribute);
if (item == null) { /* ... */ }


typeof null is "object"... this is what getAttribute seems to return when the attribute is missing. See documentation of element.getAttribute, specifically the notes section. It is suggested that you can use hasAttribute.


try this:

if (!item)
{
    continue;
}
else
{
    item = item.match(/[^\d+;#][\w\W]+/);
    itemIDs[item] = 1 ;
}

this proofs if the item is null or undefined. is this true, it continues the loop.


getAttribute : return type object


you should compare return value to null

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜