热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Javascript-检查数组的值[重复]-Javascript-checkarrayforvalue[duplicate]

Thisquestionalreadyhasananswerhere:这个问题已经有了答案:HowdoIcheckifanarrayincludes

This question already has an answer here:

这个问题已经有了答案:

  • How do I check if an array includes an object in Javascript? 40 answers
  • 如何检查数组是否包含Javascript中的对象?40的答案

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/

3 个解决方案

#1


70  

If you don't care about legacy browsers:

如果您不关心遗留浏览器:

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

if you do care 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 )

#2


6  

Try this:

试试这个:

// this will fix old browsers
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(value) {
    for (var i = 0; i 

#3


3  

This should do it:

这应该这样做:

for (var i = 0; i 

jsFiddle

jsFiddle


推荐阅读
author-avatar
手机用户2502913853
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有