English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
findIndex()The method returns the index of the first element in the array that satisfies the provided test function.
findIndex()The method calls the function once for each element in the array:
When the elements in the array return true when tested, findIndex() returns the index position of the element that meets the conditions, and the subsequent values will not call the execution function
If there is no element that meets the conditions, it will return -1
Note: The findIndex() method does not change the original array.
Note: The function will not be executed for an empty array for findIndex().
array.findIndex(callback, thisArg) array.findIndex(function(element, index, arr), thisArg)
var num = [1, 30, 39, 29, 10, 13]; var val = num.findIndex(myFunc); function myFunc(element) { return element >= 18; }Test and See‹/›
See alsofind()A method that returns the value of the element found in the array instead of its index.
The numbers in the table specify the first browser version that fully supports the findIndex() method:
Method | |||||
findIndex() | 45 | 25 | 32 | 8 | 12 |
Parameter | Description |
---|---|
callback | A function that runs for each element in the array. Function parameters:
|
thisArg | Optional. The value passed to the function is generally the "this" value. If this parameter is empty, "undefined" will be passed to the "this" value |
Return value: | If the element passes the test, it is in the array.Index; otherwise it is-1 |
---|---|
JavaScript Version: | ECMAScript 6 |
The following example returns the index of an element in the array that is a prime number; if there is no prime number, it returns-1:
var array1 = [1, 15, 17, 24, 29, 10, 13]; function isPrime(element) { var start = 2; while (start <= Math.sqrt(element)) { if (element % start < 1) { return false; } else { start++; } } return element > 1; } function myFunc1() { document.getElementById("result").innerHTML = array1.findIndex(isPrime); }Test and See‹/›