-->

[removed] compare variable against array of values

2020-05-28 08:05发布

问题:

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}

回答1:

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));



回答2:

Just try with:

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


回答3:

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.



回答4:

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 ... 
}


回答5:

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;

};

}

}