开发者

Testing for undeclared variable

开发者 https://www.devze.com 2023-02-22 13:01 出处:网络
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 followi

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开发者_StackOverflow中文版 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"      
        }


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.


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.

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 {
   ...
}
0

精彩评论

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

关注公众号