Індекс масиву JavaScriptOf ()

Метод JavaScript Array indexOf () повертає перший індекс присутності елемента масиву або -1, якщо його не знайдено.

Синтаксис indexOf()методу:

 arr.indexOf(searchElement, fromIndex)

Тут arr - це масив.

indexOf () Параметри

indexOf()Метод приймає в:

  • searchElement - Елемент для пошуку в масиві.
  • fromIndex (необов’язково) - індекс, з якого починається пошук. За замовчуванням це 0 .

Повернене значення з indexOf ()

  • Повертає перший індекс елемента в масиві, якщо він присутній хоча б один раз.
  • Повертає -1, якщо елемент не знайдено в масиві.

Примітка: indexOf() порівнює searchElementз елементами масиву, використовуючи сувору рівність (подібно до оператора triple-equals або ===).

Приклад 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 ()

Цікаві статті...