views:

61

answers:

3

Mind has gone blank this afternoon and cant for the life of me figure out the right way to do this:

if(i!="3" && i!="4" && i!="5" && i!="6" && i!="7" && i!="8" && i!="9" && i!="2" && i!="19" && i!="18" && i!="60" && i!="61" && i!="50" && i!="49" && i!="79" && i!="78" && i!="81" && i!="82" && i!="80" && i!="70" && i!="90" && i!="91" && i!="92" && i!="93" && i!="94"){

//do stuff

}

all those numbers need to be in an array, then i can check to see if "i" is not equal to any 1 of them.

thanks >.<

+2  A: 
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;  
  };  
}  
meder
seeing this just makes me love jQuery even more.
fearofawhackplanet
Yeh me too, thanks meder works perfectly
Adam
A: 

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.

SimpleCoder
It's very bad practice to use `for...in` on arrays.
Andy E
I wouldn't call it bad practice, as long as you know what you're doing. I've added a check: `typeof cantbe[j] === "number"`.
SimpleCoder
no, it's still bad practice.
lincolnk
How is it bad practice?
SimpleCoder
@SimpleCoder, because `for-in` is meant to *enumerate* object properties, to *iterate* over array objects, a sequential loop is always the best, [more details here](http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript/3010848#3010848).
CMS
@CMS, ah that makes sense, thank you
SimpleCoder
A: 

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
}
digitalFresh
One benefit of using `indexOf` is that it's already built into most modern browsers.
meder