将表达式从三元运算符转换为逻辑运算符



我使用三元运算符编写了以下条件语句:

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.label0,因为无论b如何,c && a都不可能为true;如果ctrue,则c && a也为真,因此不计算b,因为无论b如何,整个条件表达式都必须为真。

在我们的例子中,(form.label || ' ')被保证为真,因为' '是真的。所以最后你的表达变成了:

(isRequired && (form.label || ' ')) || customMessage

最新更新