Metóda indexového poľa JavaScript Array vracia prvý index výskytu prvku poľa alebo -1, ak sa nenájde.
Syntax indexOf()
metódy je:
arr.indexOf(searchElement, fromIndex)
Tu je arr pole.
parametre indexOf ()
indexOf()
Metóda berie v:
- searchElement - prvok, ktorý sa má nájsť v poli.
- fromIndex (voliteľné) - index, na ktorom sa má začať vyhľadávanie. Predvolene je to 0 .
Vrátiť hodnotu z indexOf ()
- Vráti prvý index prvku v poli, ak je prítomný aspoň raz.
- Vráti hodnotu -1, ak sa prvok v poli nenachádza.
Poznámka: indexOf()
porovnáva sa searchElement
s prvkami poľa pomocou prísnej rovnosti (podobná operátoru triple-equals alebo ===
).
Príklad 1: Použitie metódy indexOf ()
var priceList = (10, 8, 2, 31, 10, 1, 65); // indexOf() returns the first occurance var index1 = priceList.indexOf(31); console.log(index1); // 3 var index2 = priceList.indexOf(10); console.log(index2); // 0 // second argument specifies the search's start index var index3 = priceList.indexOf(10, 1); console.log(index3); // 4 // indexOf returns -1 if not found var index4 = priceList.indexOf(69.5); console.log(index4); // -1
Výkon
3 0 4 -1
Poznámky:
- Ak fromIndex> = array.length , pole sa nevyhľadáva a vráti sa -1 .
- Ak fromIndex <0 , index sa počíta dozadu. Napríklad -1 označuje index posledného prvku atď.
Príklad 2: Nájdenie všetkých výskytov prvku
function findAllIndex(array, element) ( indices = (); var currentIndex = array.indexOf(element); while (currentIndex != -1) ( indices.push(currentIndex); currentIndex = array.indexOf(element, currentIndex + 1); ) return indices; ) var priceList = (10, 8, 2, 31, 10, 1, 65, 10); var occurance1 = findAllIndex(priceList, 10); console.log(occurance1); // ( 0, 4, 7 ) var occurance2 = findAllIndex(priceList, 8); console.log(occurance2); // ( 1 ) var occurance3 = findAllIndex(priceList, 9); console.log(occurance3); // ()
Výkon
(0, 4, 7) (1) ()
Príklad 3: Vyhľadanie, či Element existuje, iné Pridanie prvku
function checkOrAdd(array, element) ( if (array.indexOf(element) === -1) ( array.push(element); console.log("Element not Found! Updated the array."); ) else ( console.log(element + " is already in the array."); ) ) var parts = ("Monitor", "Keyboard", "Mouse", "Speaker"); checkOrAdd(parts, "CPU"); // Element not Found! Updated the array. console.log(parts); // ( 'Monitor', 'Keyboard', 'Mouse', 'Speaker', 'CPU' ) checkOrAdd(parts, "Mouse"); // Mouse is already in the array.
Výkon
Element sa nenašiel! Pole bolo aktualizované. ('Monitor', 'Klávesnica', 'Myš', 'Reproduktor', 'CPU') Myš je už v poli.
Odporúčané čítanie: JavaScript Array.lastIndexOf ()