[英]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.