Ako zistiť, či pole obsahuje určitý reťazec v JavaScripte/jQuery?

Vie mi niekto povedať, ako zistiť, či sa v poli vyskytuje "specialword"? Príklad:

categories: [
    "specialword"
    "word1"
    "word2"
]

jQuery ponúka $.inArray:

Všimnite si, že inArray vracia index nájdeného prvku, takže 0 znamená, že prvok je prvý v poli. -1 znamená, že prvok nebol nájdený.

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>

Upraviť o 3,5 roka neskôr

$.inArray je v skutočnosti obal pre Array.prototype.indexOf v prehliadačoch, ktoré ho podporujú (v súčasnosti takmer všetky), pričom v tých, ktoré ho nepodporujú, poskytuje shim. Je to v podstate ekvivalentné pridaniu shimu do Array.prototype, čo je idiomatickejší/JSish spôsob, ako robiť veci. MDN poskytuje takýto kód. V dnešnej dobe by som radšej využil túto možnosť, ako používať 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

Upraviť o ďalšie 3 roky neskôr

Bože, 6,5 roka?!

Najlepšou možnosťou v modernom Javascripte je Array.prototype.includes:

var found = categories.includes('specialword');

Žiadne porovnávanie a žiadne mätúce výsledky -1. Robí to, čo chceme: vracia true alebo false. V starších prehliadačoch je možné ho polyfillovať pomocou kódu na 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
Komentáre (22)

Tu máte:

$.inArray('specialword', arr)

Táto funkcia vráti kladné celé číslo (index poľa danej hodnoty) alebo -1, ak sa daná hodnota v poli nenašla.

Živá ukážka: http://jsfiddle.net/simevidas/5Gdfc/

Pravdepodobne ju budete chcieť použiť takto:

if ( $.inArray('specialword', arr) > -1 ) {
    // the value is in the array
}
Komentáre (0)

Môžete použiť cyklus for:

var found = false;
for (var i = 0; i < categories.length && !found; i++) {
  if (categories[i] === "specialword") {
    found = true;
    break;
  }
}
Komentáre (3)