Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 == 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!

like image 782
Travis Avatar asked May 28 '10 20:05

Travis


2 Answers

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
}
like image 99
Li0liQ Avatar answered Sep 20 '22 16:09

Li0liQ


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)

like image 32
Prescott Avatar answered Sep 21 '22 16:09

Prescott