如何检查jQuery对象是否存在于数组中?
鉴于item
和array
,我想知道item
是否存在array
。如何检查jQuery对象是否存在于数组中?
item
是一个jQuery对象,例如, $(".c")
。你可以假设item.length == 1
。
array
是一个jQuery对象数组,例如, [$(".a"), $(".b")]
。此数组中的每个项目可能表示0,1个或更多个对象。
这里是我认为实现这个:(live demo here)
function inArray(item, arr) {
for (var i = 0; i < arr.length; i++) {
var items = $.makeArray(arr[i]);
for (var k = 0; k < items.length; k++) {
if (items[k] == item[0]) {
return true;
}
}
}
return false;
}
你能找到一个更优雅的实现?
例子:
HTML:
<div class="a">Hello</div>
<div class="a">Stack</div>
<div class="a">Overflow</div>
<div class="b">Have</div>
<div class="b">a</div>
<div class="b">nice</div>
<div class="b">day!</div>
<div class="c">Bye bye</div>
JS:
console.log(inArray($(".a").eq(2), [$(".a"), $(".b")])); // true
console.log(inArray($(".b").eq(3), [$(".a"), $(".b")])); // true
console.log(inArray($(".c"), [$(".a"), $(".b")])); // false
console.log(inArray($(".a").eq(2), [$(".b")])); // false
console.log(inArray($(".a").eq(2), [])); // false
console.log(inArray($(".c"), [$("div")])); // true
据Felix的建议:
[$(selector1), $(selector2), ... ]
可以简化为
$(selector1, selector2, ...)
或
$(selector1).add(selector2)...
,然后它可以实现为:
function inArray(item, arr) {
return (arr.index(item) != -1);
}
太棒了!谢谢! – 2016-03-02 02:50:28
好的解决方案!但我不认为这真的需要一个函数包装器 - 尽管OP是在它自己的函数中,只是在函数内部做一行就足够了。 – Leith 2017-04-10 01:13:24
怎么样
if(jQuery.inArray(some, array) === -1)
{
//process data if "some" is not in array
}
else
{
//process if "some" is in array
}
虽然upvoted多次,这不适用于包含jQuery对象的数组(这是OP所要求的)。使用jQuery的.index()方法,查看Misha自己的答案,找到正确的解决方案。 – Jpsy 2013-10-25 09:51:27
此解决方案不适用于jquery元素数组 – user590849 2015-02-25 15:30:23
不适用于对象数组。先阅读。 – Craig 2016-07-20 18:30:16
if($.inArray("valueYouWantToFind", nameOfTheArray) == true) {
Your code;
}
Eg.,
var userChoice = ["yes"];
if($.inArray('yes',userChoice) == true) {
alert("found");
}
data = [
{val:'xxx',txt:'yyy'},
{val:'yyy',txt:'aaa'},
{val:'bbb',txt:'ccc'}
];
var dummyArray = [];
var distinctValueArray = [];
$.each(data, function (index, firstobject) {
//push first element of object in both dummy array and distinct array.
if (index == 0) {
distinctValueArray.push(firstobject);
dummyArray.push(firstobject.txt);
}
else {
//started from 2nd index.
if ($.inArray(firstobject.txt, dummyArray) == -1) {
distinctValueArray.push(firstobject);
}
dummyArray.push(firstobject.txt);
}
});
dummyArray.length=0;
是否必须是一个数组?你为什么不使用jQuery对象和['.index()'](http://api.jquery.com/index/)? – 2012-01-07 10:37:18
@Felix:我想你的意思是使用'$(“.a,.b”)'。听起来很合理! – 2012-01-07 10:48:34
或者你可以使用['add()'](http://api.jquery.com/add/)构建jQuery对象。 – 2012-01-07 10:57:27