[英]My function doesn't return run after first statement
So I'm making a Rock Paper Scissors function that takes to value and return: win lose or tied but is not returning anything after the first block.所以我正在制作一个 Rock Paper Scissors 函数,它需要价值和回报:赢输或平局,但在第一个块之后不返回任何东西。 Here's my code :
这是我的代码:
function playRound(playerSelection, computerSelection){
if(playerSelection === "rock" && computerSelection === "scissors") {
return "wins";
}
else if(computerSelection === "paper") {
return "lost"
}
else{
return "tied";
}
if(playerSelection === "paper" && computerSelection === "rock") {
return "wins";
}
else if(computerSelection === "scissors") {
return "lost"
}
else{
return "tied";
}
if(playerSelection === "scissors" && computerSelection === "paper") {
return "wins";
}
else if(computerSelection === "rock") {
return "lost";
}
else{
return "tied";
}
}
It's not returning anything because your logic is flawed.它没有返回任何东西,因为您的逻辑有缺陷。
Your logic is (from the first block):你的逻辑是(从第一个块):
playerSelection === "rock"
&& computerSelection === "scissors"
playerSelection === "rock"
&& computerSelection === "scissors"
computerSelection === "paper"
computerSelection === "paper"
What I think you meant by your code is to actually have playerSelection === "rock"
apply to the entire first block.我认为您的代码的意思是实际上让
playerSelection === "rock"
应用于整个第一个块。 So, you would need some nested if statements to capture that.因此,您需要一些嵌套的 if 语句来捕获它。
Your revised logic should resemble this:您修改后的逻辑应该类似于:
playerSelection === "rock"
): playerSelection === "rock"
):computerSelection === "scissors"
computerSelection === "scissors"
computerSelection === "paper"
computerSelection === "paper"
That being said, your check for "everything else" is a bit repetitive and there are some further optimizations that could be made.话虽如此,您对“其他一切”的检查有点重复,并且可以进行一些进一步的优化。 That being said, I've optimized the code a bit for you.
话虽如此,我已经为您优化了代码。
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
// may be worth validating that rock/paper/scissors were the only possible inputs here
return "tied";
}
switch (playerSelection) {
case "rock":
if (computerSelection === "scissors") return "wins";
if (computerSelection === "paper") return "lost";
break;
case "paper":
if (computerSelection === "rock") return "wins";
if (computerSelection === "scissors") return "lost";
break;
case "scissors":
if (computerSelection === "paper") return "wins";
if (computerSelection === "rock") return "lost";
break;
}
// error handling (no match)
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.