Kā JavaScript/jQuery meklēt, vai masīvs satur konkrētu virkni?

Vai kāds var man pateikt, kā noteikt, vai "specialword" parādās masīvā? Piemērs:

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

jQuery piedāvā $.inArray:

Tas nozīmē, ka 0 norāda, ka šis elements ir pirmais elements masīvā. -1 norāda, ka elements nav atrasts.

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>

Edit 3,5 gadus vēlāk

$.inArray faktiski ir Array.prototype.indexOf apvalks pārlūkprogrammās, kas to atbalsta (mūsdienās gandrīz visas), bet pārlūkprogrammās, kas to neatbalsta, tas nodrošina apakšsistēmu. Tas būtībā ir līdzvērtīgs Array.prototips, kas ir idiomātiskāks/JSish veids, kā to darīt. MDN ir pieejams šāds kods. Mūsdienās es izvēlētos šo iespēju, nevis jQuery ietinēju.

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

Editēt vēl 3 gadus vēlāk

Ak, 6,5 gadi?!

Labākais risinājums mūsdienu Javascript ir Array.prototype.includes:

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

Nav salīdzinājumu un nav mulsinošu -1 rezultātu. Tas dara to, ko mēs vēlamies: atgriež true vai false. Vecākām pārlūkprogrammām tas ir aizpildāms izmantojot kodu 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āri (22)

Lūk, šeit:

$.inArray('specialword', arr)

Šī funkcija atgriež veselu pozitīvu skaitli (dotās vērtības masīva indeksu) vai -1, ja dotā vērtība masīvā nav atrasta.

Live demo: http://jsfiddle.net/simevidas/5Gdfc/

Iespējams, jūs vēlaties to izmantot šādi:

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

Varat izmantot for cilpu:

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