gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:07:03 24 4
gpt4 key购买 nike

我有一个如下所示的 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");
}

演示: http://jsfiddle.net/azWLC/4/

关于javascript - 如何确定对象是否在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16614021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com