最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Better method of checking a bunch of conditions - Stack Overflow

programmeradmin7浏览0评论

I'm new to javascript and still ing 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" ) {?

I'm new to javascript and still ing 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" ) {?

Share Improve this question asked Jul 26, 2013 at 12:55 Joel G MathewJoel G Mathew 8,10115 gold badges61 silver badges93 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 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).

A regex would be shorter and works everywhere :

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

FIDDLE

var ars = ["DOMAIN_SERIAL", "MAIN_DOMAINNAME", "DOMAIN_REFRESH"];
if(ars.some(function(ar){ return a === ar; })){
     // do smth
}

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

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}) {
发布评论

评论列表(0)

  1. 暂无评论