将表达式从三元转换为逻辑运算符
Translate expression from ternary to logical operators
我使用三元运算符编写了以下条件语句:
form?.label ? (isRequired ? (form.label) : customMessage) : isRequired ? ' ' : customMessage
如何仅使用逻辑运算符来编写这一行?
首先,请注意您的代码等同于:
isRequired ? (form.label ? form.label : ' ') : customMessage
效率稍微高一些,因为如果 isRequired
为假,它不会测试 form.label
。
现在,form.label ? form.label : ' '
意味着我们想要 form.label
、 或 ,如果它是假的,其他的东西。这可以用惰性逻辑 or 运算符编写:form.label || ' '
.
所以我们得到:
isRequired ? (form.label || ' ') : customMessage
一般来说,如果保证 a
始终为真,则 c ? a : b
等同于 (c && a) || b
。这是可行的,因为两个逻辑运算符是惰性的:如果 c
为假,则不会评估 a
,因为无论 b
为何,c && a
都不可能为真;如果 c
为 true
,则 c && a
也为真,因此 b
不被计算,因为无论 b
.[= 整个条件表达式必须为真32=]
在我们的例子中,(form.label || ' ')
保证为真,因为 ' '
为真。所以最后你的表情变成了:
(isRequired && (form.label || ' ')) || customMessage
我使用三元运算符编写了以下条件语句:
form?.label ? (isRequired ? (form.label) : customMessage) : isRequired ? ' ' : customMessage
如何仅使用逻辑运算符来编写这一行?
首先,请注意您的代码等同于:
isRequired ? (form.label ? form.label : ' ') : customMessage
效率稍微高一些,因为如果 isRequired
为假,它不会测试 form.label
。
现在,form.label ? form.label : ' '
意味着我们想要 form.label
、 或 ,如果它是假的,其他的东西。这可以用惰性逻辑 or 运算符编写:form.label || ' '
.
所以我们得到:
isRequired ? (form.label || ' ') : customMessage
一般来说,如果保证 a
始终为真,则 c ? a : b
等同于 (c && a) || b
。这是可行的,因为两个逻辑运算符是惰性的:如果 c
为假,则不会评估 a
,因为无论 b
为何,c && a
都不可能为真;如果 c
为 true
,则 c && a
也为真,因此 b
不被计算,因为无论 b
.[= 整个条件表达式必须为真32=]
在我们的例子中,(form.label || ' ')
保证为真,因为 ' '
为真。所以最后你的表情变成了:
(isRequired && (form.label || ' ')) || customMessage