繁体   English   中英

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

[英]How to check if jQuery object exist in array?

给定一个item和一个array ,我想知道item存在于array

item是一个jQuery对象,例如$(".c") 您可以假设item.length == 1

array是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

根据费利克斯的建议:

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

$(selector1, selector2, ...)

要么

$(selector1).add(selector2)...

然后它可以实现为:

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

现场演示

关于什么

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

在这里阅读: http//api.jquery.com/jQuery.inArray/

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

 Eg.,
 var userChoice = ["yes"];
 if($.inArray('yes',userChoice) == true) {
                    alert("found");
                }
console.log(!!~$.inArray("a", ["a", "b", "c"]));
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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM