Kann mir jemand sagen, wie ich erkennen kann, ob "specialword" in einem Array vorkommt? Beispiel:
categories: [
"specialword"
"word1"
"word2"
]
jQuery bietet $.inArray
:
Beachten Sie, dass inArray den Index des gefundenen Elements zurückgibt, so dass 0
anzeigt, dass das Element das erste im Array ist. Die Zahl "1" zeigt an, dass das Element nicht gefunden wurde.
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>
Bearbeitung 3,5 Jahre später
$.inArray" ist effektiv ein Wrapper für "Array.prototype.indexOf" in Browsern, die es unterstützen (heutzutage fast alle), während es in Browsern, die es nicht unterstützen, ein Shim darstellt. Es ist im Wesentlichen gleichbedeutend mit dem Hinzufügen eines Shims zu Array.prototype
, was eine idiomatischere/JSish Art ist, die Dinge zu tun. MDN bietet solchen Code. Heutzutage würde ich diese Option nehmen, anstatt den jQuery-Wrapper zu verwenden.
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
Weitere 3 Jahre später bearbeiten
Meine Güte, 6,5 Jahre?!
Die beste Option für dieses in modernem Javascript ist Array.prototype.includes
:
var found = categories.includes('specialword');
Keine Vergleiche und keine verwirrenden -1
Ergebnisse. Es tut, was wir wollen: es gibt true
oder false
zurück. Für ältere Browser ist es polyfillable unter Verwendung des Codes bei 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
Hier ist es:
$.inArray('specialword', arr)
Diese Funktion gibt eine positive ganze Zahl zurück (den Array-Index des angegebenen Wertes), oder -1
, wenn der angegebene Wert nicht im Array gefunden wurde.
Live-Demo:
Wahrscheinlich wollen Sie diese Funktion wie folgt verwenden:
if ( $.inArray('specialword', arr) > -1 ) {
// the value is in the array
}
Sie können eine "for"-Schleife verwenden:
var found = false;
for (var i = 0; i < categories.length && !found; i++) {
if (categories[i] === "specialword") {
found = true;
break;
}
}