Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

javascript - How to check if jQuery object exist in array?

Given an item and an array, I would like to know if item exist in array.

item is a jQuery object, e.g. $(".c"). You can assume that item.length == 1.

array is an array of jQuery objects, e.g. [$(".a"), $(".b")]. Each item in this array may represent 0, 1, or more objects.

Here is how I thought to implement this: (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;
}

Can you find a more elegant implementation?


Example:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to Felix's suggestion:

[$(selector1), $(selector2), ... ] can be simplified to

$(selector1, selector2, ...)

or

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

and then it can be implemented as:

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

Live demo here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...