JavaScript Array indexOf ()

El método JavaScript Array indexOf () devuelve el primer índice de ocurrencia de un elemento de la matriz, o -1 si no se encuentra.

La sintaxis del indexOf()método es:

 arr.indexOf(searchElement, fromIndex)

Aquí, arr es una matriz.

Parámetros indexOf ()

El indexOf()método incluye:

  • searchElement: el elemento que se ubicará en la matriz.
  • fromIndex (opcional): el índice en el que comenzar la búsqueda. Por defecto, es 0 .

Valor de retorno de indexOf ()

  • Devuelve el primer índice del elemento en la matriz si está presente al menos una vez.
  • Devuelve -1 si el elemento no se encuentra en la matriz.

Nota: se indexOf() compara searchElementcon los elementos del Array usando igualdad estricta (similar al operador triple-igual o ===).

Ejemplo 1: uso del método 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

Salida

 3 0 4 -1

Notas:

  • Si fromIndex> = array.length , no se busca en el array y se devuelve -1 .
  • Si fromIndex <0 , el índice se calcula hacia atrás. Por ejemplo, -1 denota el índice del último elemento y así sucesivamente.

Ejemplo 2: encontrar todas las ocurrencias de un elemento

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

Salida

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

Ejemplo 3: Encontrar si el elemento existe más Agregar el elemento

 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.

Salida

¡Elemento no encontrado! Se actualizó la matriz. ('Monitor', 'Teclado', 'Ratón', 'Altavoz', 'CPU') El ratón ya está en la matriz.

Lectura recomendada: JavaScript Array.lastIndexOf ()

Articulos interesantes...