简体   繁体   中英

assigning variables only if undefined in javascript

I'm trying to extract two keywords from a url in this format

localhost:3000/"charactername"/"realmname"

where I want to exctract "charactername" and "realmname" and assign them to variables.

I use:

var charactername = req.url.split("/")[1];
console.log(charactername);
var realmname  = req.url.split("/")[2];
console.log(realmname);

Everything works fine and dandy at first, but then it seems a request is made for a "favicon.ico", and my variables become undefined since there is a new request url. I tried solving this by encapsulating the code snippet in an if statement like this:

if(req.url !== '/favicon.ico'){ 
var charactername = req.url.split("/")[1];
console.log(charactername);
var realmname  = req.url.split("/")[2];
console.log(realmname);
}

The console.log outputs tells me the variables are set to their correct values, it never says it is undefined so it seems to work.. However, when the next part of the code is executed:

if(charactername.length > 0){
            res.writeHead(200, {'Content-Type': 'text/html'});
            renderer.view("header", {}, res);

            //get json from battle.net
            var characterProfile = new Profile(charactername, realmname);

            //on "end"
            characterProfile.on("end", function(profileJSON){
                //Show profile
                //Store values we need
                var values = {
                    avatarURL: profileJSON.thumbnail,
                    charactername: profileJSON.name,
                    realmname: profileJSON.realm,
                    level: profileJSON.level
                }
                //Simple response
                renderer.view("profile", values, res);
                renderer.view("footer", {}, res);
                res.end();
            });

I get an error saying cannot read property length of undefined. So it seems the variables become undefined somehow anyway. Anyone got a clue on how to solve this?

if(x === undefined){
  //do something
}

This checks if the variable is undefined, however I suggest you check what is causing the error in the first place.

if(charactername && charactername.length > 0){

...

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.

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