Javascript: compare a variable with an 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 cut 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} 
+6
source share
5 answers

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

Using

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

The 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)); 
+15
source

Just try:

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

Another 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 a comment by Anthony Grist

This method works if you know what these values ​​will be (i.e. they are not dynamic), and your array contains a series of consecutive numerical values.

+3
source

Since indexOf() has some browser compatibility issues and requires an additional step (to compare the result with -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 ... } 
+3
source

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

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

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; 

};

}

}

+1
source

All Articles