- Изучаем JavaScript: поиск в массиве с помощью методов indexOf и lastIndexOf
- Поиск элемента в массиве — знакомство с методом indexOf
- Примеры применения метода indexOf()
- Поиск элемента в массиве — знакомство с методом lastIndexOf()
- Поиск элемента в массиве — примеры использования метода lastIndexOf()
- Array.prototype.indexOf()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Using indexOf()
- Finding all the occurrences of an element
- Finding if an element exists in the array or not and updating the array
- Using indexOf() on sparse arrays
- Calling indexOf() on non-array objects
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- Как узнать индекс элемента в массиве js
Изучаем JavaScript: поиск в массиве с помощью методов indexOf и lastIndexOf
В статье рассказывается о том, как использовать методы JavaScript indexOf и lastIndexOf для определения расположения элемента внутри массива.
Поиск элемента в массиве — знакомство с методом indexOf
Чтобы определить расположение элемента в массиве, можно воспользоваться методом indexOf() . Он возвращает индекс первого вхождения элемента, либо -1 , если он не найден.
Ниже приведен синтаксис метода indexOf() :
Array.indexOf(searchElement, fromIndex)
Метод indexOf() принимает два аргумента. searchElement -это элемент, который нужно найти в массиве. fromIndex – это индекс массива, с которого нужно начать поиск.
Аргумент fromIndex в качестве значения может принимать как положительное, так и отрицательное целое число. Если значение аргумента fromIndex будет отрицательным, метод indexOf() начнет поиск по всему массиву плюс значение fromIndex . Если опустить аргумент fromIndex , то метод начнет поиск с элемента 0 .
Учтите, что метод JavaScript array indexOf() при сравнении searchElement с элементами в массиве, использует алгоритм строгого равенства , схожий с оператором “ тройное равно ” (===) .
Примеры применения метода indexOf()
Предположим, что есть массив scores , в котором содержится шесть чисел:
var scores = [10, 20, 30, 10, 40, 20];
В следующем примере метод indexOf() используется для поиска элементов в массиве scores :
console.log(scores.indexOf(10)); // 0 console.log(scores.indexOf(30)); // 2 console.log(scores.indexOf(50)); // -1 console.log(scores.indexOf(20)); // 1
В примере используется fromIndex с отрицательными значениями:
console.log(scores.indexOf(20,-1)); // 5 (fromIndex = 6+ (-1) = 5) console.log(scores.indexOf(20,-5)); // 1 (fromIndex = 6+ (-5) = 1)
Предположим, что есть массив объектов. У каждого из них два свойства: name и age :
Следующие выражение возвращает -1 , даже если у первого элемента массива guests и searchElement будут одинаковые значения свойств name и age . Так как это два разных объекта:
console.log(guests.indexOf(< name: 'John Doe', age: 30 >)); // -1
Иногда нужно находить индексы всех упоминаний элемента в массиве. В приведенном ниже примере для этого в функции find() используется метод массива JavaScript indexOf() :
function find(needle, haystack) < var results = []; var idx = haystack.indexOf(needle); while (idx != -1) < results.push(idx); idx = haystack.indexOf(needle, idx + 1); >return results; >
В следующем примере функция find() используется для возврата массива с позициями числа 10 в массиве scores :
console.log(find(10,scores)); // [0, 3] JavaScript array lastIndexOf method
Поиск элемента в массиве — знакомство с методом lastIndexOf()
У массивов есть еще один метод — lastIndexOf() , который предлагает почти тот же функционал, что и indexOf() .
Синтаксис метода lastIndexOf() :
Array.lastIndexOf(searchElement[, fromIndex = Array.length – 1])
Метод возвращает индекс последнего вхождения searchElement в массиве. Если элемент не найден, будет возвращено значение -1 .
В отличие от метода JavaScript indexOf() , lastIndexOf() сканирует массив в обратном направлении, начиная от значения fromIndex .
Представленное ниже выражение возвращает последние индексы чисел 10 и 20 в массиве scores :
console.log(scores.lastIndexOf(10));// 3 console.log(scores.lastIndexOf(20));// 5
Поиск элемента в массиве — примеры использования метода lastIndexOf()
Так как число 50 не находится в массиве, следующее выражение вернет -1 .
console.log(scores.lastIndexOf(50));// -1
Мы научились использовать методы JavaScript indexOf() string и lastIndexOf() для поиска элементов в массиве.
Array.prototype.indexOf()
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Try it
Syntax
indexOf(searchElement) indexOf(searchElement, fromIndex)
Parameters
Element to locate in the array.
Zero-based index at which to start searching, converted to an integer.
Return value
The first index of the element in the array; -1 if not found.
Description
The indexOf() method compares searchElement to elements of the array using strict equality (the same algorithm used by the === operator). NaN values are never compared as equal, so indexOf() always returns -1 when searchElement is NaN .
The indexOf() method skips empty slots in sparse arrays.
The indexOf() method is generic. It only expects the this value to have a length property and integer-keyed properties.
Examples
Using indexOf()
The following example uses indexOf() to locate values in an array.
const array = [2, 9, 9]; array.indexOf(2); // 0 array.indexOf(7); // -1 array.indexOf(9, 2); // 2 array.indexOf(2, -1); // -1 array.indexOf(2, -3); // 0
You cannot use indexOf() to search for NaN .
const array = [NaN]; array.indexOf(NaN); // -1
Finding all the occurrences of an element
const indices = []; const array = ["a", "b", "a", "c", "a", "d"]; const element = "a"; let idx = array.indexOf(element); while (idx !== -1) indices.push(idx); idx = array.indexOf(element, idx + 1); > console.log(indices); // [0, 2, 4]
Finding if an element exists in the array or not and updating the array
function updateVegetablesCollection(veggies, veggie) if (veggies.indexOf(veggie) === -1) veggies.push(veggie); console.log(`New veggies collection is: $veggies>`); > else console.log(`$veggie> already exists in the veggies collection.`); > > const veggies = ["potato", "tomato", "chillies", "green-pepper"]; updateVegetablesCollection(veggies, "spinach"); // New veggies collection is: potato,tomato,chillies,green-pepper,spinach updateVegetablesCollection(veggies, "spinach"); // spinach already exists in the veggies collection.
Using indexOf() on sparse arrays
You cannot use indexOf() to search for empty slots in sparse arrays.
.log([1, , 3].indexOf(undefined)); // -1
Calling indexOf() on non-array objects
The indexOf() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length .
const arrayLike = length: 3, 0: 2, 1: 3, 2: 4, 3: 5, // ignored by indexOf() since length is 3 >; console.log(Array.prototype.indexOf.call(arrayLike, 2)); // 0 console.log(Array.prototype.indexOf.call(arrayLike, 5)); // -1
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jun 27, 2023 by MDN contributors.
Your blueprint for a better internet.
Как узнать индекс элемента в массиве js
Чтобы узнать индекс элемента в массиве в JS, можно воспользоваться методом indexOf() . Этот метод вернёт первый индекс, по которому указанный элемент находится в массиве:
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); // => 1
Если такого элемента в массиве нет, то метод вернет -1
console.log(beasts.indexOf('giraffe')); // => -1
Помимо стандартных возможностей JS, узнать индекс элемента массива можно с помощью метода из библиотеки Lodash _.findIndex():
Метод возвращает индекс первого элемента в массиве, который удовлетворяет условию. Если ни один из элементов не удовлетворяет условию поиска, возвращается -1. Этот метод отлично ладит с массивами, элементами которых являются объекты. Обратимся к примеру ниже:
const users = [ 'user': 'kris', 'active': false >, 'user': 'john', 'active': false >, 'user': 'luk', 'active': true > ]; const findUserItem = _.findIndex(users, 'user': 'john', 'active': false >); console.log(findUserItem); // => 1 - индекс искомого элемента
В примере выше всё понятно, давайте посмотрим возможности этого метода в следующем примере.
const findUserItem = _.findIndex(users, ['active', false]); console.log(findUserItem); // => 0
В примере выше нам не важно имя пользователя, нам просто нужно найти пользователя, у которого был бы неактивный статус. И данный метод нам в этом отлично поможет.