开发者

shorter conditionals in js

开发者 https://www.devze.com 2023-01-03 23:05 出处:网络
I have conditionals like this: if (foo ==开发者_如何学运维 \'fgfg\' || foo == \'asdf\' || foo == \'adsfasdf\') {

I have conditionals like this:

if (foo ==开发者_如何学运维 'fgfg' || foo == 'asdf' || foo == 'adsfasdf') {
// do stuff

}

Surely there's a faster way to write this?

Thanks.


You might consider a switch-case statement

switch(foo) {
  case "fgfg":
  case "asdf":
  case "adsfasdf":
    // ...
}

It's not really any shorter, but could be more readable depending on how many conditions you use.


I would keep the conditionals the way they are. Any clever way of shortening them would make the code less idiomatic and less readable.

Now, if you do care about readability, you could define a function to do the comparison:

if( foo_satisfies_condition(foo) ) {
  // ...
}

Or:

if( is_month_name(foo) {
  // ...
}

If you give the function a name that faithfully describes what it does, it will be easier to understand the intent of the code.

How you implement that function would depend on how many comparisons you need. If you have a really large number of strings you're comparing against, you could use a hash. The implementation details are irrelevant when reading the calling code, though.


if (/^(fgfg|asdf|adsfasdf)$/.test(foo)) {

or:

if (["fgfg", "asdf", "adsfasdf"].indexOf(foo) != -1) {

Cross-browser support for Array.indexOf is still limited. Also, these are faster to write, probably not faster to run.


No need for using indexOf or a regex if you just use a hash table:

var things = { 'fgfg' : 1, 'asdf' : 1, 'asdfasdf' : 1 };
if ( things[foo] ) { 
    ... 
}


Here's a easy way:

String.prototype.testList = function(lst) {
 lst = lst.split('|');
 for(var i=0; i<lst.length; i++){
  if (this == lst[i]) return true;
 }
 return false;
};

To use this function, you can just do this:

if (foo.testList('fgfg|asdf|adsfasdf')) {

You can also rename testList to whatever you want, and change the delimiter from | to anything you want.


Depending on the situation you could do..

//At some point in your code
var vals = new Array('fgfg', 'asdf', 'adsfasdf');
//...
if(vals.indexOf(foo) >= 0)


Ternary operator looks good if you like and has else


Use tilde (~) for a shorter expression

if (~["fgfg", "asdf", "adsfasdf"].indexOf(foo)) {
    //do stuff
}
0

精彩评论

暂无评论...
验证码 换一张
取 消