David Garcia
David Garcia

Reputation: 2696

Javascript: compare variable against array of values

In javascript I am doing the following which works fine.

if (myVar == 25 || myVar == 26 || myVar == 27 || myVar == 28)
 {
   //do something
 }

How can I shorten it? something like the following.

if (myVar IN ('25','26','27','28')) {
    //do something
   }

or

if(myVar.indexOf("25","26","27","28") > -1) ) {//do something}

Upvotes: 8

Views: 48968

Answers (6)

Mahesh Mahadar
Mahesh Mahadar

Reputation: 31

var validValues = [25, 26, 27, 28]
var myVar = 25

if (validValues.includes(myVar)) {
    //do something
}

Upvotes: 0

Sandeeproop
Sandeeproop

Reputation: 1776

if ( [25, 26, 27, 28].indexOf(myVar) > -1 ) {}

Array.indexOf will work fine for all modern browsers(FF, Chrome, >IE8), just a word of caution is that Array.indexOf will not work for IE8. If you want to make it work in IE8 please use the below code:

window.onload = function() {

if (!Array.prototype.indexOf) {

Array.prototype.indexOf = function(elt /*, from*/) {
  var len = this.length >>> 0;
  var from = Number(arguments[1]) || 0;
  from = (from < 0) ? Math.ceil(from) : Math.floor(from);
  if (from < 0) {
    from += len;
  }
  for (; from < len; from++) {
    if (from in this && this[from] === elt){
      return from;
  }
}
return -1;

};

}

}

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You can use Array.indexOf(), it returns the first index at which a given element can be found in the array, or -1 if it is not present.

Use

var arr = [25, 26, 27, 28];
console.log(arr.indexOf(25) > -1);
console.log(arr.indexOf(31) > -1);


Array.includes() method can also be used it returns boolean.

var arr = [25, 26, 27, 28];
console.log(arr.includes(25));
console.log(arr.includes(31));

Upvotes: 25

JLRishe
JLRishe

Reputation: 101652

Since indexOf(), has some browser compatibility issues and requires an extra step (of comparing the result to -1), an alternative, cross-browser approach is the following jQuery utility method (if you include jQuery in your project) :

if($.inArray(myVar, [25, 26, 27, 28]) > -1) {
     // ... do something ... 
}

Upvotes: 3

R3tep
R3tep

Reputation: 12854

Other way :

myVar = (myVar == parseInt(myVar) ? myVar : false); //to check if variable is an integer and not float
if ( myVar >= 25 && myVar <= 28){}

Live demo

Edit based on the comment of Anthony Grist

This way works if you know what those values are going to be (i.e. they're not dynamic) and your array contains a series of consecutive numeric values.

Upvotes: 3

hsz
hsz

Reputation: 152206

Just try with:

if ( [25, 26, 27, 28].indexOf(myVar) > -1 ) {}

Upvotes: 9

Related Questions