gpt4 book ai didi

javascript - 如何将多个 else if 语句转换为三元运算符

转载 作者:行者123 更新时间:2023-11-28 17:04:33 25 4
gpt4 key购买 nike

我如何将此if/else语句转换为三元运算符而不是使用if/else语句。我知道这对于大多数 JavaScript 开发人员来说很简单,但对我来说却很困惑。

  if(this.props.usersWhoAreTyping.length === 0) {
return null
} else if(this.props.usersWhoAreTyping.length === 1 ){
return <p>{this.props.usersWhoAreTyping[0]} is typing...</p>
}
else if(this.props.usersWhoAreTyping.length > 1){
return <p>{this.props.usersWhoAreTyping.join('and')} are typing...</p>
}

我的尝试是这样的

 {this.props.usersWhoAreTyping.length === 0 ?  (
null
): (
<p>{this.props.usersWhoAreTyping[0]} is typing...</p>
)}
// not sure how to include the 2nd else if statement in this ternary operator

最佳答案

如果我正确理解你的意图,就不需要三元组。

示例:

render() {
const { usersWhoAreTyping } = this.props

return (
<div>
{usersWhoAreTyping.length === 1 && <p>{usersWhoAreTyping[0]} is typing...</p>}
{usersWhoAreTyping.length > 1 && <p>{usersWhoAreTyping.join('and')} are typing...</p>}
</div>
)

关于javascript - 如何将多个 else if 语句转换为三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56227492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com