Consider the following:
var a = 'jesus'; if(a == 'something' || a == 'nothing' || a=='anything' || a=='everything'){ alert('Who cares?'); }
Is there a way to make this shorter?
Is there anything in Javascript like if (a=='bbb'||'ccc')
?
In addition, can jQuery help here?
To check if a variable is equal to all of multiple values, use the logical AND (&&) operator to chain multiple equality comparisons. If all comparisons return true , all values are equal to the variable. Copied! We used the logical AND (&&) operator to chain multiple equality checks.
You can compare 2 variables in an if statement using the == operator.
JavaScript provides three different value-comparison operations: === — strict equality (triple equals) == — loose equality (double equals) Object.is()
You could use this...
if (["something", "nothing", "anything", "everything"].includes(a)) { alert('Who cares?'); }
If you're stuck with older browser support...
if (["something", "nothing", "anything", "everything"].indexOf(a) > -1) { alert('Who cares?'); }
You also tagged it jQuery, so if you need to support older browsers without Array.prototype.indexOf()
, you could use $.inArray()
.
With a regex:
if (/^(something|nothing|anything|everything)$/.exec('jesus')) alert('Who cares?');
Or the opposite:
/^(something|nothing|anything|everything)$/.exec('jesus')||alert('Who cares?');
[Update] Even shorter ;-)
if (/^(some|no|any|every)thing$/.exec('jesus')) alert('Who cares?');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With