Qualcuno può dirmi come rilevare se "parola speciale"
appare in un array? Esempio:
categories: [
"specialword"
"word1"
"word2"
]
jQuery offre $.inArray
:
Si noti che inArray restituisce l'indice dell'elemento trovato, quindi 0
indica che l'elemento è il primo nell'array. -1
indica che l'elemento non è stato trovato.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];
var categoriesNotPresent = ['word', 'word', 'word'];
var foundPresent = $.inArray('specialword', categoriesPresent) > -1;
var foundNotPresent = $.inArray('specialword', categoriesNotPresent) > -1;
console.log(foundPresent, foundNotPresent); // true false
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Modifica 3,5 anni dopo
$.inArray
è effettivamente un wrapper per Array.prototype.indexOf
nei browser che lo supportano (quasi tutti di questi tempi), mentre fornisce uno shim in quelli che non lo fanno. È essenzialmente equivalente ad aggiungere uno shim ad Array.prototype
, che è un modo più idiomatico/JSish di fare le cose. MDN fornisce tale codice. In questi giorni prenderei questa opzione, piuttosto che usare il wrapper jQuery.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];
var categoriesNotPresent = ['word', 'word', 'word'];
var foundPresent = categoriesPresent.indexOf('specialword') > -1;
var foundNotPresent = categoriesNotPresent.indexOf('specialword') > -1;
console.log(foundPresent, foundNotPresent); // true false
Modifica altri 3 anni dopo
Cavolo, 6 anni e mezzo?!
La migliore opzione per questo in Javascript moderno è Array.prototype.includes
:
var found = categories.includes('specialword');
Nessun confronto e nessun confuso risultato -1
. Fa quello che vogliamo: restituisce vero
o falso
. Per i vecchi browser è polifillabile usando il codice su MDN.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];
var categoriesNotPresent = ['word', 'word', 'word'];
var foundPresent = categoriesPresent.includes('specialword');
var foundNotPresent = categoriesNotPresent.includes('specialword');
console.log(foundPresent, foundNotPresent); // true false
Ecco a voi:
$.inArray('specialword', arr)
Questa funzione restituisce un intero positivo (l'indice dell'array del valore dato), o -1
se il valore dato non è stato trovato nell'array.
Dimostrazione vivente:
Probabilmente vorrete usarla in questo modo:
if ( $.inArray('specialword', arr) > -1 ) {
// the value is in the array
}