为什么这段代码不起作用。这是一个基本的摇滚,纸张,剪刀游戏,如果userChoice不是“摇滚”,“纸张”或“剪刀”,我试图让它再次询问答案。我该怎么做因为这不起作用。仅供参考我很新,所以我要的可能是非常基本的。 :)
var userChoice = prompt("Do you choose rock, paper or scissors?");
console.log("User: " + userChoice);
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 === "paper") {
if(choice2 === "rock"){
return"paper wins";
} else if(choice2 === "scissors"){
return"scissors wins";
}
} else if (choice1 === "scissors") {
if(choice2 === "paper"){
return"scissors wins";
} else if(choice2 === "rock"){
return"rock wins";
}
} else if (choice1 === "rock") {
if(choice2 === "scissors"){
return"rock wins";
} else if(choice2 === "paper"){
return"paper wins";
}
} else {
tryAgain();
}
};
var tryAgain = function(){
compare(userChoice, computerChoice);
}
compare(userChoice, computerChoice);
答案 0 :(得分:1)
您可以在最后的其他声明中加入:
else {
userChoice = prompt("Invalid entry. Try again:");
console.log(compare(userChoice, computerChoice));
return '';
}
编辑:在此处尝试:
link:jsfiddle.net/k1ssedbyf1re/r7B9M /
我假设您可能在Codecademy中这样做。要在JSFiddle中查看答案,请右键单击页面,转到“检查元素”。然后是“控制台”,你会看到结果:)
答案 1 :(得分:0)
将前两行移至tryAgain内(并将其名称更改为'try'左右)。
现在当你打电话给tryAgain时,它没有从用户那里得到新的选择,只是继续使用相同的..