Kan iemand mij vertellen hoe ik kan detecteren of "specialword"
voorkomt in een array? Voorbeeld:
categories: [
"specialword"
"word1"
"word2"
]
jQuery biedt $.inArray
:
Merk op dat inArray de index van het gevonden element retourneert, dus 0
geeft aan dat het element de eerste in de array is. -1
geeft aan dat het element niet is gevonden.
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 jaar later
$.inArray
is in feite een wrapper voor Array.prototype.indexOf
in browsers die dat ondersteunen (tegenwoordig bijna allemaal), terwijl het een shim biedt in browsers die dat niet ondersteunen. Het is in wezen gelijk aan het toevoegen van een shim aan Array.prototype
, wat een meer idiomatische/JSish manier is om dingen te doen. MDN biedt dergelijke code. Tegenwoordig zou ik deze optie nemen, in plaats van de jQuery wrapper te gebruiken.
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 nog eens 3 jaar later
Gosh, 6.5 jaar?!
De beste optie hiervoor in modern Javascript is Array.prototype.includes
:
var found = categories.includes('specialword');
Geen vergelijkingen en geen verwarrende -1
resultaten. Het doet wat we willen: het geeft true
of false
terug. Voor oudere browsers is het polyfillable met behulp van de code op 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
Alsjeblieft:
$.inArray('specialword', arr)
Deze functie geeft een positief geheel getal terug (de array index van de gegeven waarde), of -1
als de gegeven waarde niet in de array werd gevonden.
Live demo:
Je wilt dit waarschijnlijk als volgt gebruiken:
if ( $.inArray('specialword', arr) > -1 ) {
// the value is in the array
}