[英]javascript typeof item === “undefined” never returns true
In the following code sample, typeof item === "undefined" never returns true.在以下代码示例中,typeof item === "undefined" 永远不会返回 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"
我正在尝试从 XML 获取属性,如果 XML 中不存在该属性,它将返回“未定义”,但我无法捕获它是否返回未定义,萤火虫将“typeof item”显示为“对象” "
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编辑:我将条件更改为 if(item == undefined),代码现在按预期工作
Edit2: Double checked it, item variable was never null, it was "undefined" Edit2:仔细检查,项目变量从来不是 null,它是“未定义”
getAttribute returns an object (valid object or a null object). getAttribute 返回 object(有效的 object 或 null 对象)。 So the check
(typeof item === "undefined")
is not correct.所以检查
(typeof item === "undefined")
不正确。 It should be (item === null)
.它应该是
(item === null)
。
Some browser's implementation of getAttribute
may return an empty string if the attribute doesn't exist.如果属性不存在,某些浏览器的
getAttribute
实现可能会返回一个空字符串。 You could test for both null and ""
, or alternatively use hasAttribute
.您可以同时测试 null 和
""
,或者使用hasAttribute
。
if(rows[i].hasAttribute(attribute))
{
// do stuff...
}
https://developer.mozilla.org/en/DOM/element.getAttribute https://developer.mozilla.org/en/DOM/element.getAttribute
It's because typeof null === 'object'
(contrary to the common sense).这是因为
typeof null === 'object'
(与常识相反)。 You should check if getAttrbiute
's return value equals null
.您应该检查
getAttrbiute
的返回值是否等于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. typeof null
是"object"
......这是 getAttribute 似乎在缺少属性时返回的内容。 See documentation of element.getAttribute , specifically the notes section.请参阅element.getAttribute的文档,特别是注释部分。 It is suggested that you can use hasAttribute .
建议您可以使用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.这证明该项目是 null 还是未定义。 is this true, it continues the loop.
这是真的吗,它继续循环。
getAttribute
: return type object
getAttribute
: 返回类型object
you should compare return value to null
您应该将返回值与
null
进行比较
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.