gpt4 book ai didi

javascript - 我的 javascript 循环在完成所有 if else 语句之前中断

转载 作者:行者123 更新时间:2023-12-02 16:29:59 26 4
gpt4 key购买 nike

我正在尝试编写一个 PIN 码猜测游戏,并写了一堆 if else 语句,但在我输入第一个 PIN 码(正确或不正确)后它停止工作,有人可以告诉我发生了什么事吗?

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

最佳答案

问题是您在guessNum 函数中创建的变量gNum 仅存在于该处。 JavaScript 是函数作用域的。

当你到达 if (gNum != pswd) {... gNum 根本不存在这一行时。让guessNum返回值,并在与if相同的范围内创建实际的gNum变量。

function guessNum() {
return prompt("What do you think the number is?")
}

...
var gNum = guessNum();
if (gNum != pswd) {
...

我还建议您研究 while 循环,以避免这些嵌套的 if。继续努力吧! :)

关于javascript - 我的 javascript 循环在完成所有 if else 语句之前中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28390496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com