Методът JavaScript Array indexOf () връща първия индекс на поява на елемент от масив или -1, ако не е намерен.
Синтаксисът на indexOf()
метода е:
arr.indexOf(searchElement, fromIndex)
Тук arr е масив.
indexOf () Параметри
В indexOf()
метода се в:
- searchElement - Елементът, който трябва да се намери в масива.
- fromIndex (по избор) - Индексът, с който започва търсенето. По подразбиране е 0 .
Върната стойност от indexOf ()
- Връща първия индекс на елемента в масива, ако той присъства поне веднъж.
- Връща -1, ако елементът не е намерен в масива.
Забележка: indexOf()
сравнява searchElement
с елементи на масив, използвайки строго равенство (подобно на троен равнява оператор или ===
).
Пример 1: Използване на метод 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
Изход
3 0 4 -1
Бележки:
- Ако fromIndex> = array.length , масивът не се търси и -1 се връща.
- Ако fromIndex <0 , индексът се изчислява назад. Например -1 означава индекса на последния елемент и т.н.
Пример 2: Намиране на всички прояви на елемент
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); // ()
Изход
(0, 4, 7) (1) ()
Пример 3: Намиране дали елементът съществува иначе Добавяне на елемента
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.
Изход
Елементът не е намерен! Актуализиран масивът. ('Monitor', 'Keyboard', 'Mouse', 'Speaker', 'CPU') Мишката вече е в масива.
Препоръчително четене: JavaScript Array.lastIndexOf ()