Metodas „JavaScript Array indexOf ()“ pateikia pirmąjį masyvo elemento tikimybės indeksą arba -1, jei jo nerandama.
indexOf()
Metodo sintaksė yra tokia:
arr.indexOf(searchElement, fromIndex)
Čia arr yra masyvas.
indexOf () parametrai
indexOf()
Metodas trunka:
- searchElement - elementas, kurį reikia rasti masyve.
- fromIndex (neprivaloma) - rodyklė, nuo kurios pradedama paieška. Pagal numatytuosius nustatymus tai yra 0 .
Grąžinimo vertė iš indexOf ()
- Grąžina pirmąjį masyvo elemento indeksą, jei jis yra bent kartą.
- Grąžina -1, jei elementas nerandamas masyve.
Pastaba: indexOf()
palyginama searchElement
su masyvo elementais, naudojant griežtą lygybę (panaši į operatoriaus trigubai lygi arba ===
).
1 pavyzdys: metodo indexOf () naudojimas
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
Rezultatas
3 0 4 -1
Pastabos:
- Jei fromIndex> = masyvo.length , masyvo neieškoma ir grąžinama -1 .
- Jei fromIndex <0 , indeksas skaičiuojamas atgal. Pavyzdžiui, -1 žymi paskutinio elemento indeksą ir pan.
2 pavyzdys: surasti visus elemento atvejus
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); // ()
Rezultatas
(0, 4, 7) (1) ()
3 pavyzdys: surasti, ar elementas egzistuoja kitur. Elemento pridėjimas
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.
Rezultatas
Elementas nerastas! Atnaujino masyvą. („Monitorius“, „Klaviatūra“, „Pelė“, „Garsiakalbis“, „Procesorius“) Pelė jau yra masyve.
Rekomenduojamas skaitymas: JavaScript Array.lastIndexOf ()