[removed] compare variable against array of values

前端 未结 5 863
滥情空心
滥情空心 2021-02-06 07:12

In javascript I am doing the following which works fine.

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

相关标签:
5条回答
  • 2021-02-06 07:14

    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 ... 
    }
    
    0 讨论(0)
  • 2021-02-06 07:17

    Just try with:

    if ( [25, 26, 27, 28].indexOf(myVar) > -1 ) {}
    
    0 讨论(0)
  • 2021-02-06 07:20

    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.

    0 讨论(0)
  • 2021-02-06 07:24

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

    0 讨论(0)
  • 2021-02-06 07:31

    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;
    

    };

    }

    }

    0 讨论(0)
提交回复
热议问题