简体   繁体   English

我将如何简化这个严格的平等表达

[英]How would I shorthand this strict equality expression

Is there any way to shorthand the if expression without introducing a new variable? 有什么方法可以在不引入新变量的情况下简化if表达式?

if ((c2 === 'RED') || (c2 === 'GREEN') || (c2 === 'BLUE')) {
 return true;
} else {
 return false
}

I figured it would be something like: if ((c2 === ('RED'|| 'GREEN' ||'BLUE'))) 我想像是这样: if ((c2 === ('RED'|| 'GREEN' ||'BLUE')))

Array.indexOf does strict checking, so you could do Array.indexOf严格检查,因此您可以执行

if ( ['RED','GREEN','BLUE'].indexOf(c2) !== -1 ) {...

and as it already returns a boolean, you could just return it directly without the condition 并且由于它已经返回了布尔值,因此您可以直接将其返回而无需附加条件

You can shorten it by taking advantage of the fact that the comparisons give you boolean results, so you don't need an explicit return with the boolean value: 您可以利用比较为您提供布尔结果这一事实来缩短它,因此您不需要使用布尔值的显式return

return ((c2 === 'RED') || (c2 === 'GREEN') || (c2 === 'BLUE'));

You can also make an object: 您还可以创建一个对象:

var targets = { RED: 1, GREEN: 1, BLUE: 1 };
return !!targets[c2]; // !! turns the 1 into true

(You could use true in the object to avoid the !! .) (您可以在对象中使用true来避免!! 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM