5

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" ) {?

Joel G Mathew
  • 7,561
  • 15
  • 54
  • 86

5 Answers5

13

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

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 5
    8 upvotes within a minute for such a trivial answer O_o (and none on the question). – Rob W Jul 26 '13 at 12:58
  • @RobW What can I say? Simpler questions help more users in SO than more complicated and specific ones. If it makes you feel any better I have some answers that are 5 pages long and cite new concepts from multiple recent articles - I guess not many people found stuff like [this](http://stackoverflow.com/a/15648868/1348195) helpful. – Benjamin Gruenbaum Jul 26 '13 at 12:59
2

A regex would be shorter and works everywhere :

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

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
1
var ars = ["DOMAIN_SERIAL", "MAIN_DOMAINNAME", "DOMAIN_REFRESH"];
if(ars.some(function(ar){ return a === ar; })){
     // do smth
}
karaxuna
  • 26,752
  • 13
  • 82
  • 117
1

Should mention the switch statement as it should be working fine with the example given in the question.

switch(a) {
  case('MAIN_DOMAINAME'):
  case('DOMAIN_SERIAL'):
  case('DOMAIN_REFRESH'):
  case('DOMAIN_RETRY'):
    console.log('Go wild.');
  break;
}

Not as lightweight as the other answers, but it's readable and matches (a === b).

estrar
  • 1,373
  • 4
  • 12
  • 37
0

I prefer the regex solution already provided by adeneo, but if you want something that matches the

if a is one of (...

wording from the question reasonably closely you can do this:

if (a in list("MAIN_DOMAINNAME", "DOMAIN_SERIAL", "DOMAIN_REFRESH", "DOMAIN_RETRY")) {
    // do something                 (rest of list omitted to avoid scrolling)
}

by providing a helper function to turn the list into an object:

function list() {
   var o={}, i;
   for (i=0; i < arguments.length; i++) o[arguments[i]] = true;
   return o;
}

Of course you can omit the helper function and just use an object literal, but that's ugly:

if (a in {"MAIN_DOMAINNAME":1, "DOMAIN_SERIAL":1, "DOMAIN_REFRESH":1}) {
nnnnnn
  • 147,572
  • 30
  • 200
  • 241