really confused because I have no errors but I can't see which bit of my code is producing this:
rock
scissors
"scissors wins"
I've done a console.log to see the results as they come out so I know this is the wrong part but I can't remember where that bit is in my code now.
Code is:
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);
Any idea which bit is doing it?
Cheers!
if (choice1 === "paper");
Because of the semicolon, the next block is always entered
{
if (choice2 === "rock")
{
return "paper wins";
}
Here you have else
instead of else if
, so it ignores the condition and returns "scissors wins"
else (choice2 === "scissors")
{
return "scissors wins";
}
}
如果不需要分号,那么您已经在多个地方做到了
if (choice1 === "paper"); // <--
You put ;
after your if
s, you shouldn't.
If you put a ;
then the if
's scope end after the condition, the remaining code is executed after, like it's just a scope definition.
if (choice1 === "paper");
should be
if (choice1 === "paper")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.