Javascript If statement, looking through an array

后端 未结 3 550
攒了一身酷
攒了一身酷 2021-02-08 22:54

Mind has gone blank this afternoon and can\'t for the life of me figure out the right way to do this:

if(i!=\"3\" && i!=\"4\" && i!=\"5\" &&a         


        
3条回答
  •  梦谈多话
    2021-02-08 23:45

    var a = [3,4,5,6,7,8,9];
    
    if ( a.indexOf( 2 ) == -1 ) { 
       // do stuff
    }
    

    indexOf returns -1 if the number is not found. It returns something other than -1 if it is found. Change your logic if you want.

    Wrap the numbers in quotes if you need strings ( a = ['1','2'] ). I don't know what you're dealing with so I made them numbers.

    IE and other obscure/older browsers will need the indexOf method:

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

提交回复
热议问题