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 works 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...
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.