Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise way to compare against multiple values [duplicate]

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?

like image 214
FatDogMark Avatar asked Dec 06 '12 04:12

FatDogMark


People also ask

How do you compare multiple values in an if statement?

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.

How do you compare values in two variables?

You can compare 2 variables in an if statement using the == operator.

How do you compare two things in JavaScript?

JavaScript provides three different value-comparison operations: === — strict equality (triple equals) == — loose equality (double equals) Object.is()


2 Answers

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().

like image 131
alex Avatar answered Nov 15 '22 22:11

alex


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?');​ 
like image 42
Christophe Avatar answered Nov 15 '22 23:11

Christophe