简体   繁体   English

测试未声明的变量

[英]Testing for undeclared variable

I'm trying to parse an RSS feed using javascript. 我正在尝试使用JavaScript解析RSS feed。 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. 有时,提要有多个类别,因此我想检查第2项是否有任何内容。如果不检查,则会出现错误,并且在使用以下代码进行检查时,也会出现错误。 (I'm setting var cat2 simply as a test if the variable is defined or not). (我只是将var cat2设置为测试是否定义了变量)。

var catItem = item.getElementsByTagName("category").item(2).text;

        if (typeof catItem != 'undefined'){
            var cat2 = "1"
        }
        else{

            var cat2 = "2"      
        }

Checking if a variable is undefined can be done via the following as answered above, if (typeof catItem !== 'undefined'){ ... } 如果(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. 未声明的变量是尚未使用“ var”关键字声明的变量。

var catItem = document.getElementsByTagName("category")[2];
var cat2 = "2";

if (typeof catItem !== 'undefined') {
    cat2 = "1";
}

You could also shorten this up by using a ternary operation: 您还可以通过使用三元操作来缩短此时间:

var catItem = document.getElementsByTagName("category")[2];
var cat2 = catItem ? "2" : "1";

You're code would only work if there is an element in range of position 2. 您的代码仅在位置2范围内有一个元素时才起作用。

Why not just do: 为什么不做:

if(item.getElementsByTagName("category").length > 1) {

You can try something like this: 您可以尝试如下操作:

var catItem = item.getElementsByTagName("category");
if(catItem[1]) {
   ...
}
else {
   ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM