[英]Simplify nested ternary in Javascript
I have the following code:我有以下代码:
return this.condition1
? condition2
? true
: false
: false
Is there a way to write this without using true
false
?有没有办法在不使用
true
false
情况下编写它?
Yes, you can simplify that;是的,你可以简化它; you don't need any ternary operators:
你不需要任何三元运算符:
return this.condition1 && condition2;
Performing a test in order to choose either true
or false
is redundant.执行测试以选择
true
或false
是多余的。 You can use !!
你可以用
!!
to turn a "truthy" value into a boolean value, and if the test expressions already provide boolean values (such as >
or <
comparisons) then you've already got the values you need.将“真实”值转换为布尔值,如果测试表达式已经提供布尔值(例如
>
或<
比较),那么您已经获得了所需的值。
return this.condition1 && condition2;
should be sufficient for using in if
and other conditions.应该足以在
if
和其他条件下使用。 Note that it's not strictly equivalent javascript to your code.请注意,它并不严格等同于您的代码的 javascript。
To be certain to return true
or false
(as the primitive boolean
values), you need to coerce this as a boolean like this :为了确定返回
true
或false
(作为原始boolean
值),您需要将其强制为布尔值,如下所示:
return !!(this.condition1 && condition2);
(this is really for the sake of exactitude, and I would style recommend the first simpler version in most cases, though). (这真的是为了精确起见,不过在大多数情况下,我会推荐第一个更简单的版本)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.