Javascript - 检查数组的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11015469/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:01:37  来源:igfitidea点击:

Javascript - check array for value

javascriptarrays

提问by Nick

I have a simple array with bank holidays:

我有一个带银行假期的简单数组:

var bank_holidays = ['06/04/2012','09/04/2012','07/05/2012','04/06/2012','05/06/2012','27/08/2012','25/12/2012','26/12/2012','01/01/2013','29/03/2013','01/04/2013','06/05/2013','27/05/2013'];

I want to do a simple check to see if certain dates exist as part of that array, I have tried:

我想做一个简单的检查,看看某些日期是否作为该数组的一部分存在,我试过:

if('06/04/2012' in bank_holidays) { alert('LOL'); }
if(bank_holidays['06/04/2012'] !== undefined) { alert 'LOL'; }

And a few other solutions with no joy, I have also tried replacing all of the forwarded slashes with a simple 'x' in case that was causing issues.

和其他一些不高兴的解决方案,我还尝试用简单的“x”替换所有转发的斜杠,以防引起问题。

Any recommendations would be much appreciated, thank you!

任何建议将不胜感激,谢谢!

(edit) Here's a jsFiddle- http://jsfiddle.net/ENFWe/

(编辑)这是一个jsFiddle- http://jsfiddle.net/ENFWe/

回答by Florian Margaine

If you don't care about legacy browsers:

如果您不关心旧版浏览器:

if ( bank_holidays.indexOf( '06/04/2012' ) > -1 )

if you docare about legacy browsers, there is a shim available on MDN. Otherwise, jQuery provides an equivalent function:

如果您确实关心旧版浏览器,那么MDN上有一个 shim 可用。否则,jQuery 提供了一个等效的函数:

if ( $.inArray( '06/04/2012', bank_holidays ) > -1 )

回答by ioseb

Try this:

尝试这个:

// this will fix old browsers
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(value) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] === value) {
        return i;
      }
    }

    return -1;
  }
}

// example
if ([1, 2, 3].indexOf(2) != -1) {
  // yay!
}

回答by Barry Kaye

This should do it:

这应该这样做:

for (var i = 0; i < bank_holidays.length; i++) {
    if (bank_holidays[i] === '06/04/2012') {
        alert('LOL');
    }
}

jsFiddle

js小提琴