Skip to content Skip to sidebar Skip to footer

Javascript If Statement, Looking Through An Array

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' && i!='6' && i!='

Solution 1:

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;  

    varfrom = Number(arguments[1]) || 0;  
    from = (from < 0)  
         ? Math.ceil(from)  
         : Math.floor(from);  
    if (from < 0)  
      from += len;  

    for (; from < len; from++)  
    {  
      if (frominthis &&  
          this[from] === elt)  
        returnfrom;  
    }  
    return -1;  
  };  
}  

Solution 2:

My mind made this solution:

functionnot(dat, arr) { //"not" functionfor(var i=0;i<arr.length;i++) {
  if(arr[i] == dat){returnfalse;}
}
returntrue;
}

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]; //numbersif(not(i, check)) {
//do stuff
}

Solution 3:

This solution is cross-browser:

var valid = true;
var cantbe = [3, 4, 5]; // Fill in all your valuesfor (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.

Post a Comment for "Javascript If Statement, Looking Through An Array"