Return inside if else 并使用 fat arrow

Return inside if else and using fat arrow

当我尝试在 fat-arrow 函数的条件运算符中 return userInput 时出错。请多多指教。

使用 ES5 我的代码工作正常;

userInput = userInput.toLowerCase();
if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors' ) {
  return userInput;
} else {
  console.log('Error!');
}
console.log(getUserChoice('Paper')); // console prints 'paper'
console.log(getUserChoice('fork')); // console prints 'Error!' and `undefined`

But 当我使用 ES6 fat-arrow 和条件运算符时出现错误。 注意:我想 return userInput 立即对 if..else 语句的第一个条件求值。

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors')? return userInput : console.log('Error');
};

console.log(getUserChoice('Paper'));
console.log(getUserChoice('fork'));

出现下面的错误

  (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors')? return userInput : console.log('Error');
                                                                               ^^^^^^
SyntaxError: Unexpected token return

您需要在条件语句的开头指定 return,例如:

return (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors')? userInput : console.log('Error'); 

JavaScript有两种创建不同分支的方法:

1) if() 语句分支 一条语句或语句块

 if(cond) {
   statement1;
   statement2;
 } else statement 3

2) 分支表达式的三元运算符.

 cond ? expression1 : expression2

return 是语句,语句不能在表达式中。您要么 return 整个三元组,要么使用 if.

很久以前就介绍过三元,这跟箭头函数没有关系

这里的关键是认识到?:是一个运算符。就像 +* 等任何其他运算符一样计算它以创建新值。考虑到这一点,您就可以理解为什么 return 的位置在您的原始版本中没有意义。 return 是命令(或更准确地说是语句),而不是值。