为什么这个if / else在其他提示之前没有运行

时间:2015-10-07 17:00:06

标签: javascript

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?");

这就是我的代码,(我是初学者,只是搞乱了概念),如果输入的密码不正确,是不是应该立即将我重定向到谷歌?因为当我运行该代码时,它会在重定向之前首先提供所有提示。感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:2)

因为执行location.assign不会停止执行JavaScript,所以它会继续运行。它将在顺序JavaScript完成后执行位置分配。由于prompt会阻止当前执行,因此要完成它需要通过提示。要阻止它,只需将提示添加到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?");
}