开发者

short hand for chaining logical operators in javascript?

Is there a better way to write the following conditional in javascript?

if ( value == 1 || value == 16 || value == -500 || value == 开发者_JAVA技巧42.42 || value == 'something' ) {
  // blah blah blah
}

I hate having all of those logical ORs strung together. I'm wondering if there is some kind of shorthand.

Thanks!


var a = [1, 16, -500, 42.42, 'something'];
var value = 42;
if (a.indexOf(value) > -1){
// blah blah blah
}

Upd: Utility function sample as proposed in comments:

Object.prototype.in = function(){
  for(var i = 0; i < arguments.length; i++){
    if (this == arguments[i]) return true;
  }
  return false;
}

So you can write:

if (value.in(1, 16, -500, 42.42, 'something')){
// blah blah blah
}


You could extend the array object:

Array.prototype.contains = function(obj) {
  var i = this.length;
  while (i--) {
    if (this[i] == obj) {
      return true;
    }
  }
  return false;
}

Then if you store all those values in an array you could do something like MyValues.contains(value)


nope, that is the shorthand.

as an alternative, you can do a switch

switch (value) {
case 1 :
case 16 :
case -500 :
    ....
}

which is easier to manage if you need a lot of possible values, but actually your version is shorter anyway :)


var value= -55;
switch(value){
    case 1: case 16: case -55: case 42.5: case 'something': 
        alert(value); break;        

}


switch is an acceptable choice. You can also use a map, depending on the complexity of the problem (assuming you have more than you put in your example).

var accept = { 1: true, 16: true, '-500': true, 42.42: true, something: true };
if (accept[value]) {
  // blah blah blah
}

accept could be generated progamatically from an array of course. Depends really on how much you plan on using this pattern. :/


Well, you could use a switch statement...

switch (value) {
  case 1    : // blah
              break;
  case 16   : // blah
              break;
  case -500 : // blah
              break;
  case 42.42: // blah
              break;
  case "something" : // blah
                     break;
}

If you're using JavaScript 1.6 or greater, you can use the indexOf notation on an array:

if ([1, 16, -500, 42.42, "something"].indexOf(value) !== -1) {
   // blah
}

And for the ultimate in hackiness, you can coerce the values to strings (this works for all browsers):

if ("1,16,-500,42.42,something".indexOf(value) !== -1) {
   // blah
}


In an effort to make yet another way of doing it...

if (/^(1|16|-500|42.42|something)$/.test(value)) {
  // blah blah blah
}

No need to extend array prototypes or anything, just use a quick regexp to test the value!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜