提问人:ever 提问时间:7/19/2023 更新时间:7/19/2023 访问量:41
语法错误:意外的令牌返回 -- 我不能在切换大小写中使用“return”?
Syntax Error: Unexpected token return -- I can't use 'return' in switch case?
问:
我通过这样调用它来测试我的函数:determineWinner ('rock', 'rock');
但是我收到此错误消息:
computerChoice === 'paper' ? return "Computer wins!" : return "User wins!";
^^^^^^
SyntaxError: Unexpected token return
功能如下:
const determineWinner = (userChoice, computerChoice) => {
if (userChoice === computerChoice) {
return "It's a tie!";
};
switch (userChoice) {
case 'rock':
computerChoice === 'paper' ? return "Computer wins!" : return "User wins!";
break;
case 'paper':
computerChoice === 'scissors' ? return "Computer wins!" : return "User wins!"
break;
case 'scissors':
computerChoice === 'rock' ? return "Computer wins!" : return "User wins!"
break;
};
};
determineWinner ('rock', 'rock');
我知道你不打算在函数之外使用“return”,但我认为我没有这样做?任何帮助将不胜感激,谢谢!!
答:
0赞
Ankush Gupta
7/19/2023
#1
无法从三元运算符返回。三元运算符已返回,但未显式使用关键字。相反,请尝试在某个可变变量中捕获该返回值。就您而言,您可以这样做:-
const determineWinner = (userChoice, computerChoice) => {
if (userChoice === computerChoice) {
return "It's a tie!";
};
let whoWins = '';
switch (userChoice) {
case 'rock':
whoWins = computerChoice === 'paper' ? "Computer wins!" : "User wins!";
break;
case 'paper':
whoWins=computerChoice === 'scissors' ? "Computer wins!" : "User wins!"
break;
case 'scissors':
whoWins= computerChoice === 'rock' ? "Computer wins!" : "User wins!"
break;
default:
whoWins= 'No one wins';
};
return whoWins
};
console.log(determineWinner ('rock', 'rock'));
这将绝对正常工作
评论
1赞
Zac Anger
7/19/2023
你的理由是正确的,但不需要额外的可变变量和额外的赋值。它可能是return a === b ? 'foo' : 'bar'
评论
a = condition ? b : c;
a = condition ? return b: return c;
return computerChoice === 'paper' ? "Computer wins!" : "User wins!";