【发布时间】:2020-08-14 13:00:01
【问题描述】:
我使用三元运算符编写了以下条件语句:
form?.label ? (isRequired ? (form.label) : customMessage) : isRequired ? ' ' : customMessage
如何仅使用逻辑运算符编写此行?
【问题讨论】:
标签: typescript logical-operators conditional-operator
我使用三元运算符编写了以下条件语句:
form?.label ? (isRequired ? (form.label) : customMessage) : isRequired ? ' ' : customMessage
如何仅使用逻辑运算符编写此行?
【问题讨论】:
标签: typescript logical-operators conditional-operator
首先,请注意您的代码相当于:
isRequired ? (form.label ? form.label : ' ') : customMessage
效率稍高一些,因为如果isRequired 为假,它不会测试form.label。
现在,form.label ? form.label : ' ' 意味着我们想要form.label,或如果它是假的,其他的。这可以用惰性逻辑 or 运算符编写:form.label || ' '。
所以我们得到:
isRequired ? (form.label || ' ') : customMessage
一般来说,c ? a : b 等价于 (c && a) || b,如果 a 保证始终为真。这是因为两个逻辑运算符是惰性的:如果c 为假,则不评估a,因为无论b 如何,c && a 都不能为真;如果c 是true,那么c && a 也为真,因此不会计算b,因为无论b 是什么,整个条件表达式都必须为真。
在我们的例子中,(form.label || ' ') 保证为真,因为' ' 为真。所以最后你的表达变成了:
(isRequired && (form.label || ' ')) || customMessage
【讨论】:
isRequired ? (form.label ? form.label : ' ') : customMessage 很简单:它返回form.label、' ' 或customMessage,具体取决于isRequired 和form.label 的值。但是,(isRequired && (form.label || ' ')) || customMessage 有点欺骗性:它看起来像一个条件表达式,但它实际上返回一个字符串。如果你想写六个月后看一眼就能看懂的代码,我认为三元运算符比条件运算符更适合。