JavaScript Array indexOf ()

Metoda JavaScript Array indexOf () vrne prvi indeks pojavnosti elementa matrike ali -1, če ga ne najde.

Sintaksa indexOf()metode je:

 arr.indexOf(searchElement, fromIndex)

Tu je arr matrika.

parametri indexOf ()

indexOf()Metoda je v:

  • searchElement - element, ki ga najdemo v matriki.
  • fromIndex (neobvezno) - indeks za začetek iskanja. Privzeto je 0 .

Vrnjena vrednost iz indexOf ()

  • Vrne prvi indeks elementa v matriki, če je prisoten vsaj enkrat.
  • Vrne -1, če elementa ni mogoče najti v matriki.

Opomba: indexOf() primerja se searchElementz elementi matrike z uporabo stroge enakosti (podobno kot operator triple-equals ali ===).

Primer 1: Uporaba metode 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

Izhod

 3 0 4 -1

Opombe:

  • Če fromIndex> = array.length , polja ne iščete in vrnete -1 .
  • Če je odIndex <0 , se indeks izračuna nazaj. Na primer, -1 označuje indeks zadnjega elementa itd.

Primer 2: Iskanje vseh pojavov elementa

 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); // ()

Izhod

 (0, 4, 7) (1) ()

Primer 3: Ugotovitev, ali element obstaja drugje Dodajanje elementa

 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.

Izhod

Elementa ni mogoče najti! Posodobljeno polje. ('Monitor', 'Keyboard', 'Mouse', 'Speaker', 'CPU') Miška je že v polju.

Priporočeno branje: JavaScript Array.lastIndexOf ()

Zanimive Članki...