三元运算符多语句
Ternary operator multiple statements
如果条件为真或假,我想做多件事。我试图将语句包装在 { }
中,但它不起作用。所以我的代码:
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")
这行不通。如果条件为真或假,如何添加多个语句?
谢谢。
只有当您需要想出一个 表达式(有条件地)是一件事或另一件事时,才应使用条件运算符,例如
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");
但这很难读懂,而且您的代码 reader 不希望从条件运算符中看到什么,因此应该避免。
在不打算使用结果表达式时使用条件运算符可能应该只保留用于代码高尔夫和缩小,而不是在专业源代码中,其中可读性非常重要。
您可以使用 comma operator,像这样:
const ret = true ?
(console.log("1"),
console.log("2"),
"3")
: console.log("nope");
console.log(ret);
如果条件为真或假,我想做多件事。我试图将语句包装在 { }
中,但它不起作用。所以我的代码:
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")
这行不通。如果条件为真或假,如何添加多个语句?
谢谢。
只有当您需要想出一个 表达式(有条件地)是一件事或另一件事时,才应使用条件运算符,例如
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");
但这很难读懂,而且您的代码 reader 不希望从条件运算符中看到什么,因此应该避免。
在不打算使用结果表达式时使用条件运算符可能应该只保留用于代码高尔夫和缩小,而不是在专业源代码中,其中可读性非常重要。
您可以使用 comma operator,像这样:
const ret = true ?
(console.log("1"),
console.log("2"),
"3")
: console.log("nope");
console.log(ret);