【发布时间】:2016-02-16 10:00:54
【问题描述】:
我设置了一个石头、纸、剪刀游戏,用户点击标记为“石头”、“纸”、“剪刀”的按钮,这会导致用户选择。 当我运行程序时,compareChoices() 函数总是返回“结果是平局,让我们再玩一次!”,我不明白为什么。
< article >
< button onclick = "rockPaperScissors('Rock')" > Rock < /button>
<button onclick="rockPaperScissors('Paper')">Paper</button >
< button onclick = "rockPaperScissors('Scissors')" > Scissors < /button>
</article >
< script type = "text/javascript" >
function rockPaperScissors(userchoice) {
alert("You chose " + userchoice + " ...the computer chose " + getComputerChoice() + ".");
compareChoices();
}
function getComputerChoice() {
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "Rock";
} else if (computerChoice < 0.67) {
computerChoice = "Paper";
} else {
computerChoice = "Scissors";
}
return computerChoice;
}
function compareChoices(userChoice, ComputerChoice) {
if (userChoice === ComputerChoice) {
alert("The result is a tie, let's play again!");
} else if (userChoice === "Rock") {
if (ComputerChoice === "Scissors") {
alert("Congratulations, you win!");
} else {
alert("The computer wins! Care to play again?");
}
} else if (userChoice === "Scissors") {
if (ComputerChoice === "Rock") {
alert("The computer wins, let's play again!");
} else {
alert("Yippie! You win!");
}
} else if (userChoice === "Paper") {
if (ComputerChoice === "Rock") {
alert("The computer wins. Don't give up, try again!");
} else {
alert("Hail the all mighty visitor. Give it another go!");
}
}
} < /script>
【问题讨论】:
-
你没有为
compareChoices传递任何arguments -
看起来您没有将参数传递给 compareChoices() 函数
-
这会有所帮助:
var computed = getComputerChoice(); alert("You chose " + userchoice + " ...the computer chose " + computed + "."); compareChoices(userchoice, computed); -
如果我可以提醒你,不要忘记在 JS 中所有参数都是可选的,所以在调用函数时要小心。
标签: javascript function if-statement