javascript - 如何使用一个默认条件对 3 个条件执行三元语句

标签 javascript react-native ternary-operator

是否可以在 3 个条件下执行三元运算,但只有一个默认条件?

这是我的代码:

<Button
  rounded={true}
  title='Add Address'
  backgroundColor='#2980b9'
  rightIcon={{name: 'arrow-forward'}}
  disabled={this.state.timeSlotItemSelected === null || this.state.quantityItemSelected === null ? true : false}
/>

在此,this.state.timeSlotItemSelected 是默认值。我需要的是,每当 this.state.timeSlotItemSelectedthis.state.quantityItemSelected 为 null 时,结果应该为 true,并且每当 this.state.timeSlotItemSelectedthis.state.deliveryOptionSelected 为 null,那么它也应该为 true。否则它应该是false

如何针对这两种情况执行此操作?

最佳答案

您可以通过 && 的简单组合来完成此操作和|| ,并且根本不需要三元运算符。

this.state.timeSlotItemSelected === null &&
    (this.state.quantityItemSelected === null || this.state.deliveryOptionSelected === null)

这将是true如果this.state.timeSlotItemSelected为 null,并且如果 this.state.quantityItemSelected 之一或this.state.deliveryOptionSelected为空,且 false否则。

真值表:

timeSlotItemSelected | quantityItemSelected | deliveryOptionSelected | Result
---------------------+----------------------+------------------------+-------
null                 | null                 | null                   | true
null                 | <not null>           | null                   | true
null                 | null                 | <not null>             | true
null                 | <not null>           | <not null>             | false
<not null>           | <anything>           | <anything>             | false

在这种情况下,您不需要三元运算符,因为表达式本身将返回 truefalse :<Expression> ? true : false =<Expression> .

关于javascript - 如何使用一个默认条件对 3 个条件执行三元语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54145979/

相关文章:

javascript - 如何在 JavaScript 中向数组内的对象添加值?

c - 具有多个语句的三元运算符

c++ - 如何使用中间规则操作在 Bison 中创建短路评估?

javascript - 是否有用于将多个 CSS 和 JS 文件打包和缩小为一个文件的库?

javascript - react 国家 -> 省/州 -> 城市选择器?

javascript - 如何在 AngularJS 中的 $http.post -> 解析/拒绝中绑定(bind) "this"? (现在 this = Window 对象)

ios - react native 选择文本与复选标记

amazon-web-services - 使用 Cognito 防止多个同时登录

c - 将空字符插入 snprintf

javascript - 使用 socket.emit 处理 Node.js 错误