代码之家  ›  专栏  ›  技术社区  ›  Somename

三元运算符多个语句[重复]

  •  0
  • Somename  · 技术社区  · 6 年前

    这个问题已经有了答案:

    如果条件是真是假,我想做很多事情。我试图用一个 { } 但它不起作用。所以我的代码:

    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 回复  |  直到 6 年前
        1
  •  4
  •   CertainPerformance    6 年前

    只有当需要 表达 这是(有条件地)一件或另一件事,如

    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");
    

    但这很难阅读,而且您的代码的读者从条件运算符中不会看到,因此应该避免这样做。

    当不使用结果表达式时使用条件运算符可能只保留用于代码高尔夫球和缩小,但不应保留在 专业源代码 ,其中可读性非常重要。

        2
  •  0
  •   Olian04    6 年前

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

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