测试未声明的变量
我正在尝试使用 JavaScript 解析 RSS 提要。有时一个提要有多个类别,所以我想检查第 2 项是否有任何内容。如果我不检查,我会收到错误,当我使用以下代码检查时,我也会收到错误。 (我设置 var cat2 只是为了测试变量是否已定义)。
var catItem = item.getElementsByTagName("category").item(2).text;
if (typeof catItem != 'undefined'){
var cat2 = "1"
}
else{
var cat2 = "2"
}
I'm trying to parse an RSS feed using javascript. Sometimes a feed has multiple categories so I want to check if there is anything at item 2. If I don't check I get an error and when I use the following code to check I also get an error. (I'm setting var cat2 simply as a test if the variable is defined or not).
var catItem = item.getElementsByTagName("category").item(2).text;
if (typeof catItem != 'undefined'){
var cat2 = "1"
}
else{
var cat2 = "2"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
检查变量是否未定义可以通过上面回答的以下内容来完成, if (typeof catItem !== 'undefined'){ ... }
但是,我只是想指出未定义的变量与未声明的变量不同多变的。您所要求的不是标题中所说的“测试未声明的变量”。
未定义变量是“声明”但未分配任何值的变量。未声明的变量是未使用“var”关键字声明的变量。
Checking if a variable is undefined can be done via the following as answered above, if (typeof catItem !== 'undefined'){ ... }
However, I just wanted to point out that undefined variable is not the same as an undeclared variable. What you are asking is not "Testing for undeclared variable" as you put in the title.
Undefined variable is a variable that is "declared" but not assigned any value. An undeclared variable is a variable that has not been declared with a "var" keyword.
您还可以通过使用三元运算来缩短此过程:
You could also shorten this up by using a ternary operation:
您的代码仅在位置 2 范围内存在元素时才有效。
为什么不这样做:
You're code would only work if there is an element in range of position 2.
Why not just do:
你可以尝试这样的事情:
You can try something like this: