我正在尝试编写一个pin数猜测游戏并写出一堆if else语句,但是在我输入第一个引脚(正确或不正确)后它停止工作,有人能告诉我发生了什么吗?
var ans = prompt("Do you want to play?");
if (ans == "y") {
document.getElementById("ans").innerHTML = "You answered yes.";
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = h1;
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = h2;
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = h3;
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = "You lost. :(";
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("ans").innerHTML = "You answered no.";}
这是javascript的其余部分,但我不认为问题就在那里。
var nums = [0, 0, 0, 0];
for (var idx = 0; idx < nums.length; ++idx)
{
nums[idx] = Math.floor((Math.random() * 9) + 1);
}
pswd = nums.join("")
document.getElementById("nums").innerHTML = pswd;
function guessNum() {
var gNum = prompt("What do you think the number is?")
}
if (nums[3] % 2 == 0) {
var divis = "even";
} else {
var divis = "odd";
}
var h1 = "The first number is " + nums[0]
var h2 = "The sum of the middle numbers are " + (nums[1] + nums[2])
var h3 = "The last number is " + divis
答案 0 :(得分:2)
问题是你在guessNum函数中创建的变量gNum只存在于那里。 Javascript是功能范围的。
当你到达线路时(gNum!= pswd){... gNum根本不存在。使guessNum 返回值,并在与if相同的范围内创建实际的gNum变量。
function guessNum() {
return prompt("What do you think the number is?")
}
...
var gNum = guessNum();
if (gNum != pswd) {
...
我还建议你研究while循环,以避免这些嵌套ifs。继续努力! :)