Javascript If 语句,查看数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3425291/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript If statement, looking through an array
提问by Adam Tomat
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.
所有这些数字都需要在一个数组中,然后我可以检查“ i”是否不等于其中的任何一个。
回答by meder omuraliev
var a = [3,4,5,6,7,8,9];
if ( a.indexOf( 2 ) == -1 ) { 
   // do stuff
}
indexOfreturns -1if the number is not found. It returns something other than -1if it is found. Change your logic if you want.
indexOf-1如果未找到该号码,则返回。除了-1找到它之外,它还会返回其他内容。如果你愿意,改变你的逻辑。
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.
如果需要字符串 ( a = ['1','2']),请将数字括在引号中。我不知道你在处理什么,所以我给他们做了数字。
IE and other obscure/older browsers will need the indexOfmethod:
IE 和其他晦涩/较旧的浏览器将需要该indexOf方法:
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;  
  };  
}  
回答by tcooc
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
}
回答by Chris Laplante
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;
    }
validwill be trueif iisn't a 'bad' value, falseotherwise.
valid会true,如果i不是“坏”的价值,false否则。

