2012-01-07 19 views
6

Dato uno item e uno array, vorrei sapere se item esiste in array.Come verificare se l'oggetto jQuery esiste nell'array?

item è un oggetto jQuery, ad es. $(".c"). Si può supporre che item.length == 1.

array è una matrice di oggetti jQuery, ad es. [$(".a"), $(".b")]. Ogni elemento in questa matrice può rappresentare 0, 1 o più oggetti.

Ecco come ho pensato di implementare questa: (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; 
} 

si può trovare un più elegante implementazione?


Esempio:

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

ha a essere un array? Perché non usi un oggetto jQuery e ['.index()'] (http://api.jquery.com/index/)? –

+0

@Felix: Immagino tu intenda usare '$ (". A, .b ")'. Sembra ragionevole! –

+1

Oppure puoi usare ['aggiungi()'] (http://api.jquery.com/add/) per creare l'oggetto jQuery. –

risposta

9

Secondo suggerimento di Felix:

[$(selector1), $(selector2), ... ] può essere semplificata

$(selector1, selector2, ...) 

o

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

e quindi può essere implementato come:

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

Live demo here

+0

Brillante! Grazie! –

+0

Buona soluzione! Non penso che questo abbia davvero bisogno di un wrapper di funzione, sebbene - mentre l'OP fosse nella sua funzione, solo fare una riga all'interno della funzione qui è più che sufficiente. – Leith

8

che dire

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

leggere qui: http://api.jquery.com/jQuery.inArray/

+5

Sebbene sia stato messo in aumento molte volte, questo NON funziona per una matrice che contiene oggetti jQuery (che è ciò che l'OP chiedeva). Vedi la risposta di Misha per una soluzione corretta, usando il metodo .index() di jQuery. – Jpsy

+0

Questa soluzione non funziona con array di elementi jquery – user590849

+0

Non funziona per gli array di oggetti. Leggi prima. – Craig

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

Potresti approfondire questo argomento?Le risposte "Prova questo stile" non spiegano molto e incoraggiano le stesse domande a farsi chiedere più e più volte. – Gary

+0

Accordo con il commento di cui sopra: l'elaborazione del motivo per cui questa è una risposta potrebbe aiutare tutti, specialmente dove stai utilizzando due "trucchi" di JavaScript in una riga. – 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; 
Problemi correlati