简体   繁体   中英

Why doesn't this if/else run before the other prompts

var password = prompt('Please enter your password.');
if (password!=="cat" && password!=="cow") {
console.log(password);
location.assign("http://www.google.com")
}


//The rest of prompts
var age = prompt("What is your age?");
var name = prompt('What is your name?');
var homeTown = prompt('Where are you from?');
var favoritDog = prompt("What's your favorite dog?");

So that's my code, (I'm a beginner and just messing around with concepts), if the incorrect password is put in, shouldn't it redirect me to google right away? Because when I run that code, it gives me all the prompts first before the redirect. Any help is appreciated, thank you.

Because doing location.assign will not stop the execution of JavaScript, it will keep going. It will do the location assignment after the sequential JavaScript finishes. Since prompt blocks the current execution, for it to finish it will need to go through the prompts. To prevent it simply add your prompts to an else :

var password = prompt('Please enter your password.');
if (password!=="cat" && password!=="cow") {
    console.log(password);
    location.assign("http://www.google.com")
} else {
    //The rest of prompts
    var age = prompt("What is your age?");
    var name = prompt('What is your name?');
    var homeTown = prompt('Where are you from?');
    var favoritDog = prompt("What's your favorite dog?");
}

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