Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better method of checking a bunch of conditions

Tags:

javascript

I'm new to javascript and still coming to terms with the language's nuances.

I have a piece of code where I have to check a set of conditions on a particular variable.

if (a=="MAIN_DOMAINNAME" || a=="DOMAIN_SERIAL" || a=="DOMAIN_REFRESH" || a=="DOMAIN_RETRY" || a=="DOMAIN_EXPIRE" || a=="DOMAIN_NEGTTL" || a=="MAIN_NS") {

Is there a better way to do this conditional check, like say:

if a is one of ("DOMAIN_SERIAL", "MAIN_DOMAINNAME", "DOMAIN_REFRESH" ) {?

like image 693
Joel G Mathew Avatar asked Jul 26 '13 12:07

Joel G Mathew


2 Answers

Assuming a relatively modern browser, you can use Array.indexOf (spec)

if (["DOMAIN_SERIAL", "MAIN_DOMAINNAME", "DOMAIN_REFRESH"].indexOf(a) !== -1)

Note - you can easily shim it for older browsers (see the mdn link on how).

like image 141
Benjamin Gruenbaum Avatar answered Sep 27 '22 23:09

Benjamin Gruenbaum


A regex would be shorter and works everywhere :

if ( /^(MAIN_DOMAINNAME|DOMAIN_SERIAL|DOMAIN_REFRESH|..)$/.test(a) ) {
   // do stuff
}

FIDDLE

like image 31
adeneo Avatar answered Sep 27 '22 22:09

adeneo