如何检查jQuery对象是否存在于数组中?

8
给定一个item和一个array,我想知道item是否存在于array中。 item是jQuery对象,例如$(".c")。您可以假设item.length == 1array是一组jQuery对象,例如[$(".a"), $(".b")]。该数组中的每个项目可能表示0、1或多个对象。
以下是我想实现的方法:(实时演示在此处
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

2
必须使用数组吗?为什么不使用jQuery对象和.index()方法? - Felix Kling
@Felix:我猜你的意思是使用 $(".a, .b")。听起来很合理! - Misha Moroshko
1
或者您可以使用 add() 来构建 jQuery 对象。 - Felix Kling
5个回答

10

根据Felix的建议:

[$(selector1), $(selector2), ... ] 可以简化为

$(selector1, selector2, ...)
或者
$(selector1).add(selector2)...

然后可以实现为:

function inArray(item, arr) {
  return (arr.index(item) != -1);
}

这里有演示页面


好的解决方案!虽然OP在自己的函数中,但我认为这并不需要一个函数包装器,只需在此处执行函数内的一行代码就足够了。 - Leith

8

关于什么?

if(jQuery.inArray(some, array) === -1)
{
//process data if "some" is not in array
}
else
{
//process if "some" is in array
}

read here : http://api.jquery.com/jQuery.inArray/


8
虽然被点赞很多次,但是这并不适用于包含jQuery对象的数组(这正是OP所问的)。请参考Misha自己的答案,使用jQuery的.index()方法可以得出正确的解决方案。 - Jpsy
1
此解决方案不适用于 jQuery 元素数组。 - user590849

0
if($.inArray("valueYouWantToFind", nameOfTheArray) == true) {
  Your code;
 }

 Eg.,
 var userChoice = ["yes"];
 if($.inArray('yes',userChoice) == true) {
                    alert("found");
                }

0
console.log(!!~$.inArray("a", ["a", "b", "c"]));

6
能否再详细解释一下?"试一试"式的回答并不能提供很多解释,反而会鼓励人们反复询问同样的问题。请注意,我的翻译不会对原意进行更改,只会使内容更加通俗易懂。 - Gary
同意上面的评论:详细说明为什么这是一个答案会帮助每个人,特别是当你在一行代码中使用了两个 JavaScript 的“技巧”时。 - Whymarrh

-1
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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接