gpt4 book ai didi

javascript - JavaScript 游戏的可疑错误

转载 作者:行者123 更新时间:2023-11-28 07:24:14 25 4
gpt4 key购买 nike

所以我一直在 Codecademy 上进行一些练习,并遇到了一个小问题。目标是用java脚本创建一个石头剪刀布游戏。

当我尝试运行代码时,出现以下错误:“哎呀,再试一次。当输入是剪刀和布时,您的代码返回“纸胜”而不是“未定义””

我已将问题范围缩小到“else if”,我将在下面突出显示:

    var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice);



var compare = function(choice1,choice2)
{



if(choice1 === choice2)
{
return ("The result is a tie");
}

else if(choice1 === "rock")
{

if(choice2 === "scissors")
{
return ("rock wins");
}
}
        ***else if (choice2 === "paper")
{
return ("paper wins");***
        }

else if (choice1 === "paper")
{
if (choice2 === "rock")
{
return "paper wins";
}

}
else if (choice2 === "scissors")
{
return "scissors wins";
}


else if (choice1 === "scissors")
{
if (choice2 === "rock")
{
return "rock wins";
}
}

else if (choice2 === "paper")
{
return "scissors wins";
}


};

compare(userChoice,computerChoice);

所以有趣的是,如果我编写突出显示以下内容的代码:

***

else if (choice2 === "paper") { if (choice1 === rock) {

    return ("paper wins");
}
}
<小时/>

然后一切正常运行。

我想知道为什么我会收到错误,如果代码看起来与我首先仅使用“else if”语句突出显示的代码完全合理?

最佳答案

您的 ifelse if 语句未正确嵌套。

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
console.log("Computer: " + computerChoice);



var compare = function(choice1,choice2)
{

if(choice1 === choice2)
{
return ("The result is a tie");
}

else if(choice1 === "rock")
{

if(choice2 === "scissors")
{
return ("rock wins");
}
else if (choice2 === "paper")
{
return ("paper wins");
}
}
else if (choice1 === "paper")
{
if (choice2 === "rock")
{
return "paper wins";
}
else if (choice2 === "scissors")
{
return "scissors wins";
}
}
else if (choice1 === "scissors")
{
if (choice2 === "rock")
{
return "rock wins";
}
else if (choice2 === "paper")
{
return "scissors wins";
}
}
};

compare(userChoice,computerChoice);

关于javascript - JavaScript 游戏的可疑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29877609/

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