9

以下是否有简写 -

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

4 回答 4

21

你可以使用一个数组

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

或者如果您使用的是 jquery:

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

REF - OR 运算 ( || ) 与 inArray() 的性能

于 2012-06-20T20:38:33.053 回答
12

使用正则表达式:

if ( /^(com|net|co|org|info|biz)$/i.test(tld) ) {
    // do something
}
于 2012-06-20T20:37:11.307 回答
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;
}
于 2012-06-20T20:38:13.617 回答
0

位索引速记

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*/}
于 2019-11-22T13:33:37.313 回答