三元运算符多条语句

时间:2019-08-25 21:27:55

标签: javascript reactjs ecmascript-6 ternary-operator

如果条件为真或假,我想做很多事情。我试图将语句包装在{ }中,但是它不起作用。所以我的代码:

theId == this.state.correctId ? 
          console.log("Correct Id!") :
          console.log("TRY AGAIN")

我尝试过:

theId == this.state.correctId ? 
          {console.log("Correct Id!"); //semicolon does not make any difference 
          this.setState({counter: this.state.counter+1})
          } :
          console.log("TRY AGAIN")

这不起作用。如果条件为真或假,如何添加多个语句?

谢谢。

2 个答案:

答案 0 :(得分:4)

仅当您需要提出(有条件地)一件事或另一件事的表达式时,才应使用条件运算符。例如,

const something = cond ? expr1 : expr2;

因为这里不是这种情况(并且您想登录或调用setState),所以条件运算符不合适;使用if / else代替:

if (theId == this.state.correctId) {
  console.log("Correct Id!")
  this.setState({counter: this.state.counter+1});
} else {
  console.log("TRY AGAIN");
}

您可以在技术上通过使用逗号运算符组合表达式来稍微调整原始代码:

theId == this.state.correctId
? (
  console.log("Correct Id!"),
  this.setState({counter: this.state.counter+1})
)
: console.log("TRY AGAIN");

但这很难理解,不是您的代码阅读者希望从条件运算符中看到的内容,因此应该避免。

在不使用结果表达式时使用条件运算符应该只保留用于代码查找和最小化,而不能用于易读性非常重要的专业源代码中。 / p>

答案 1 :(得分:0)

您可以使用comma operator,如下所示:

const ret = true ? 
  (console.log("1"),
   console.log("2"), 
   "3")
 : console.log("nope");
 
console.log(ret);