我有一个如下所示的 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 都可以。
最佳答案
$.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");
}
关于javascript - 如何确定对象是否在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16614021/