因此,我正在制作一个Rock Paper Scissors函数,该函数需要取值并返回:输赢或并列,但在第一个程序段之后不返回任何东西。这是我的代码:
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";
}
}
答案 0 :(得分:1)
因为您的逻辑有缺陷,它没有返回任何内容。
您的逻辑是(从第一个块开始):
playerSelection === "rock"
&& computerSelection === "scissors"
computerSelection === "paper"
我认为您的代码所指的是实际上将playerSelection === "rock"
应用于整个的第一块。因此,您将需要一些嵌套的if语句来捕获它。
您修改后的逻辑应类似于:
playerSelection === "rock"
):computerSelection === "scissors"
computerSelection === "paper"
话虽这么说,您对“其他所有内容”的检查有点重复,并且可以做一些进一步的优化。话虽如此,我已经为您优化了代码。
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;
}