JavaScript Array indexOf ()

Metoda JavaScript Array indexOf () zwraca pierwszy indeks wystąpienia elementu tablicy lub -1, jeśli nie zostanie znaleziony.

Składnia indexOf()metody to:

 arr.indexOf(searchElement, fromIndex)

Tutaj arr jest tablicą.

indexOf () Parametry

indexOf()Sposób odbywa się:

  • searchElement - element do zlokalizowania w tablicy.
  • fromIndex (opcjonalny) - indeks, od którego ma się rozpocząć wyszukiwanie. Domyślnie jest to 0 .

Wartość zwracana z indexOf ()

  • Zwraca pierwszy indeks elementu w tablicy, jeśli występuje co najmniej raz.
  • Zwraca wartość -1, jeśli element nie zostanie znaleziony w tablicy.

Uwaga: indexOf() porównuje się searchElementz elementami tablicy przy użyciu ścisłej równości (podobnie do operatora potrójnego równości lub ===).

Przykład 1: Użycie metody 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

Wynik

 3 0 4 -1

Uwagi:

  • Jeśli fromIndex> = array.length , tablica nie jest przeszukiwana i zwracane jest -1 .
  • Jeśli fromIndex <0 , indeks jest obliczany wstecz. Na przykład -1 oznacza indeks ostatniego elementu i tak dalej.

Przykład 2: Znajdowanie wszystkich wystąpień elementu

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

Wynik

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

Przykład 3: Znajdowanie, czy element istnieje else Dodawanie elementu

 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.

Wynik

Nie znaleziono elementu! Zaktualizowano tablicę. („Monitor”, „Klawiatura”, „Mysz”, „Głośnik”, „Procesor”) Mysz jest już w tablicy.

Zalecana literatura : JavaScript Array.lastIndexOf ()

Interesujące artykuły...