Kaip sužinoti, ar masyve yra tam tikra eilutė, naudojant "JavaScript/jQuery"?

Ar kas nors gali man pasakyti, kaip nustatyti, ar "specialword" yra masyve? Pavyzdys:

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

jQuery siūlo $.inArray:

Atkreipkite dėmesį, kad inArray grąžina rasto elemento indeksą, todėl 0 reiškia, kad elementas yra pirmasis masyve. -1 reiškia, kad elementas nerastas.

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>

redaguoti po 3,5 metų

$.inArray iš tikrųjų yra Array.prototype.indexOf apvalkalas naršyklėse, kurios palaiko šią funkciją (šiuo metu beveik visos), o naršyklėse, kurios jos nepalaiko, tai yra "shim". Iš esmės tai yra lygiavertiška Array.prototype papildymui, o tai yra idiomatiškesnis/JSish būdas. MDN pateikia tokį kodą. Šiais laikais aš pasirinkčiau šį variantą, užuot naudojęs jQuery apvalkalą.

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

Redaguoti dar po 3 metų

Dieve, 6,5 metų?!

Šiuolaikiniame "Javascript" geriausiai tinka Array.prototype.includes:

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

Jokių palyginimų ir klaidinančių -1 rezultatų. Jis daro tai, ko norime: grąžina true arba false. Vyresnėse naršyklėse ją galima papildyti naudojant MDN pateiktą kodą.

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
Komentarai (22)

Štai taip:

$.inArray('specialword', arr)

Ši funkcija grąžina teigiamą sveiką skaičių (duotosios reikšmės indeksą masyve) arba -1, jei duotosios reikšmės masyve nerasta.

Gyvoji demonstracinė versija: http://jsfiddle.net/simevidas/5Gdfc/

Tikriausiai norėsite ją naudoti taip:

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

Galite naudoti for ciklą:

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