【发布时间】:2015-04-30 20:15:53
【问题描述】:
我正在从 Codecademy 学习 Javascript,我正在研究额外的问题,看看我是否能做到。我目前正在开发剪刀石头布游戏,如果用户输入石头、纸或剪刀以外的选项,我试图让它出现错误。我设法让它拉出错误消息,但脚本将继续运行,计算机仍会选择三者之一。
如果用户输入的不是石头或剪刀,我如何让程序停止,并且只返回错误消息而不是返回消息然后继续显示计算机的选择?
var userChoice = prompt("Do you choose rock, paper or scissors?");
if (userChoice !== "rock" || "scissors" || "paper") {
console.log("That is not one of the options");
}
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 {
return "paper wins";
}
}
else if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
} else {
return "scissors wins";
}
}
else if (choice1 === "scissors") {
if (choice2 === "paper") {
return "scissors wins";
} else {
return "rock wins";
}
}
}
compare(userChoice, computerChoice)
【问题讨论】:
-
顺便说一句,你不能比较这样的变量
-
(userChoice !== "rock" || "scissors" || "paper")应该是(userChoice !== "rock" && userChoice !== "scissors" && userChoice !== "paper")
标签: javascript