我使用三元运算符编写了以下条件语句:
form?.label ? (isRequired ? (form.label) : customMessage) : isRequired ? ' ' : customMessage
如何只使用逻辑运算符来写这行?
首先,请注意,您的代码等效于:
isRequired ? (form.label ? form.label : ' ') : customMessage
这稍微更有效,因为如果CCD_ 2为假则它不测试CCD_。
现在,form.label ? form.label : ' '
意味着我们想要form.label
、或,如果它是false,则为其他值。这可以用惰性逻辑或运算符form.label || ' '
来编写。
所以我们得到:
isRequired ? (form.label || ' ') : customMessage
一般来说,如果保证a
总是真的,则c ? a : b
等价于(c && a) || b
。这是因为两个逻辑运算符是惰性的:如果c
为false,则不计算form.label
0,因为无论b
如何,c && a
都不可能为true;如果c
是true
,则c && a
也为真,因此不计算b
,因为无论b
如何,整个条件表达式都必须为真。
在我们的例子中,(form.label || ' ')
被保证为真,因为' '
是真的。所以最后你的表达变成了:
(isRequired && (form.label || ' ')) || customMessage