Javascript If statement, looking through an array

后端 未结 3 551
攒了一身酷
攒了一身酷 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:37

    My mind made this solution:

    function not(dat, arr) { //"not" function
    for(var i=0;i<arr.length;i++) {
      if(arr[i] == dat){return false;}
    }
    return true;
    }
    
    var check = [2,3,4,5,6,7,8,9,18,19,49,50,60,61,70,78,79,80,81,82,90,91,92,93,94]; //numbers
    
    if(not(i, check)) {
    //do stuff
    }
    
    0 讨论(0)
  • 2021-02-08 23:38

    This solution is cross-browser:

    var valid = true;
    var cantbe = [3, 4, 5]; // Fill in all your values
    for (var j in cantbe)
        if (typeof cantbe[j] === "number" && i == cantbe[j]){
            valid = false;
            break;
        }
    

    valid will be true if i isn't a 'bad' value, false otherwise.

    0 讨论(0)
  • 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;  
      };  
    }  
    
    0 讨论(0)
提交回复
热议问题