[英]Can somebody explain where my mistake is in this JavaScript?
真的很困惑,因為我沒有錯誤,但是看不到代碼的哪一部分產生了這個錯誤:
rock
scissors
"scissors wins"
我已經做了一個console.log來查看結果出來,所以我知道這是錯誤的部分,但是我不記得現在代碼中的那部分。
代碼是:
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(userChoice);
console.log(computerChoice);
var compare = function(choice1,choice2) {
if (choice1 === choice2) {
return "The result is a tie!";
}
if (choice1 === "paper");
{
if (choice2 === "rock")
{
return "paper wins";
}
else (choice2 === "scissors")
{
return "scissors wins";
}
}
if (choice1 === "scissors");
{
if (choice2 === "rock")
{
return "rock wins";
}
else (choice2 === "paper")
{
return "scissors wins";
}
}
if (choice1 === "rock");
{
if (choice2 === "scissors")
{
return "rock wins";
}
else (choice2 === "paper")
{
return "paper wins";
}
}
};
compare(userChoice,computerChoice);
知道哪一點在做嗎?
干杯!
if (choice1 === "paper");
由於是分號,因此始終輸入下一個程序段
{
if (choice2 === "rock")
{
return "paper wins";
}
在這里,您擁有else
而不是else if
, else if
它將忽略條件並返回“ scissors wins”
else (choice2 === "scissors")
{
return "scissors wins";
}
}
如果不需要分號,那么您已經在多個地方做到了
if (choice1 === "paper"); // <--
你放;
在if
之后,您不應該這樣做。
如果你把一個;
然后if
的作用域在條件之后結束,其余的代碼在執行后才執行,就像它只是作用域定義一樣。
if (choice1 === "paper");
應該
if (choice1 === "paper")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.