[removed] compare variable against array of values

前端 未结 5 864
滥情空心
滥情空心 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: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;
    

    };

    }

    }

提交回复
热议问题