Is there any way to shorthand the if
expression without introducing a new variable?
if ((c2 === 'RED') || (c2 === 'GREEN') || (c2 === 'BLUE')) {
return true;
} else {
return false
}
I figured it would be something like: if ((c2 === ('RED'|| 'GREEN' ||'BLUE')))
Array.indexOf
does strict checking, so you could do
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 ((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 !!
.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.