if语句中多个OR表达式的简写

时间:2012-06-20 20:35:08

标签: javascript jquery

是否有以下简写 -

if(tld == "com" || tld == "net" || tld == "co" || tld == "org" || tld == "info" || tld == "biz")
{
    //do something;
}

4 个答案:

答案 0 :(得分:20)

你可以使用数组

if(["","com","net","co","org","info","biz"].indexOf(tld) > -1) {
     // do something
}

或者如果您使用的是jquery:

$.inArray(tld, ["com","net","co","org","info","biz"])

REF - Performance of OR operation ( || ) vs inArray()

答案 1 :(得分:12)

使用正则表达式:

if ( /^(com|net|co|org|info|biz)$/i.test(tld) ) {
    // do something
}

答案 2 :(得分:0)

你有没有想过使用switch语句?像这样的东西:

switch(tld)
{
   case 'com':
   case 'net':
   case 'co':
   ...
   ...
   // do something for all of them
   break;
   default:
   // if you want you can have default process here
   break;
}

答案 3 :(得分:0)

Bitwise IndexOf Shorthand

if (~["com", "net", "co", "org", "info", "biz"].indexOf(method)){/*Do somthing if true*/}
if (!~["com", "net", "co", "org", "info", "biz"].indexOf(method)){/*Do somthing if false*/}