如何确定对象是否在数组中?

时间:2013-05-17 16:38:57

标签: javascript jquery arrays

我有一个看起来像这样的javascript数组:

myFields = [
["fb-method","drop",false,"How did you order?"],
["fb-date","calendar",false,""],
["fb-time","drop",false,""],
["fb-location","drop",false,""],
["fb-amount","text default",false,""],
["fb-share","drop",false,""],
["fb-msg","textarea",true,""],
["next-btn","button",true,""]
]

我能够遍历数组并处理这样的特定位:

len = fields.length;

//first check to make sure required fields are filled in
for(i=0; i<len; i++) {
     a = fields[i];
     if(a[0] != "fb-method") {
        // do stuff
    }
}

如果特定元素不是数组的一部分,我需要能够(在循环之外)做某事,特别是如下所示:

["fb-location","drop",false,""]

我尝试过使用jQuery的.inArray函数,但即使返回false也会返回true。请参阅fiddle here

最好的方法是什么? jQuery或标准js很好。

3 个答案:

答案 0 :(得分:6)

$.inArray不返回bool,它返回索引(如果不存在匹配,则返回-1)。你会想要这个陈述(基于你的jsfiddle):

if(jQuery.inArray("fb-location", tmp) > -1) {
    alert("it exists");
}
else {
    alert("it doesn't exist");
}

样本: http://jsfiddle.net/azWLC/2/

<强> 更新:

正如评论中所提到的,这只是半解决方案,因为数组是多维的。我建议先使用$.map()

var tmp = [
["fb-method","drop",false,"How did you order?"],
["fb-date","calendar",false,""],
["fb-time","drop",false,""],
["fb-amount","text default",false,""],
["fb-share","drop",false,""],
["fb-msg","textarea",true,""],
["next-btn","button",true,""]
];
var values = $.map(tmp, function(n, i){
    return n[0];
});

if(jQuery.inArray("fb-location", values) > -1) {
    alert("it exists");
}
else {
    alert("it doesn't exist");
}

样本: http://jsfiddle.net/azWLC/4/

答案 1 :(得分:0)

jquery.inArray返回元素的索引。如果未找到它,则返回-1 ..除0之外的任何数字都为真,因此它表示“它存在”

答案 2 :(得分:0)

除了$.inArray,您可以Array.filter使用tmp这样:

if(  tmp.filter(function(a) {return -~a.indexOf('fb-location');}).length ) {
  // exists
}

JsFiddle

另请参阅:Array.filterArray.indexOf

使用JQuery,您将使用JQuery grep方法

if(  $.grep(tmp,function(a) {return -~a.indexOf('fb-location');}).length ) {
  // exists
}