8

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!="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.

3

3 Answers 3

18
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;  
  };  
}  
Sign up to request clarification or add additional context in comments.

1 Comment

seeing this just makes me love jQuery even more.
3

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
}

1 Comment

One benefit of using indexOf is that it's already built into most modern browsers.
1

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.

3 Comments

It's very bad practice to use for...in on arrays.
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, because for-in is meant to enumerate object properties, to iterate over array objects, a sequential loop is always the best, more details here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.