JavaScript findIndex() Method
Example
Get the index position of the first element in the array whose age is greater than or equal to 18
var
ages
=
[
3
,
10
,
18
,
20
]
;
function
checkAdult
(
age
)
{
return
age
=
18
;
}
function
myFunction
(
)
{
document
.
getElementById
(
"
demo
"
)
.
innerHTML
=
ages
.
findIndex
(
checkAdult
)
;
}
fruits Output result:
2
Try it »
Definition and Usage
The findIndex() method returns the index of the first element in the array that passes a test condition (function).
The findIndex() method calls a function once for each element in the array:
- When an element in the array returns true When true, findIndex() returns the index of the matching element, and does not call the function again for subsequent values.
- If no element meets the condition, -1 is returned
Note: For an empty array, findIndex() does not execute the function.
Note: findIndex() does not change the original value of the array.
Browser support
The numbers in the table indicate the first browser version that supports this method.
| Method | |||||
|---|---|---|---|---|---|
| findIndex() | 45.0 | 12.0 | 25.0 | 7.1 | 32.0 |
Note: IE 11 and earlier versions do not support the findIndex() method.
Syntax
array.findIndex(function(currentValue, index, arr), thisValue)
Parameters
| Parameters | Description |
|---|---|
| function(currentValue, index,arr) | Required. The function to execute for each element in the array. |
函数参数:
Parameter Description currentValue Required. The current element index Optional. The index of the current element arr Optional. The array object to which the current element belongs | Parameter | Description | *currentValue* | Required. The current element | *index* | Optional. The index of the current element | *arr* | Optional. The array object to which the current element belongs | | Parameter | Description | | *currentValue* | Required. The current element | | *index* | Optional. The index of the current element | | *arr* | Optional. The array object to which the current element belongs | | *thisValue* | Optional. The value passed to the function is generally used as the "this" value. If this parameter is empty, "undefined" is passed as the "this" value |
Technical Details
Return Value:
Returns the index of the first array element that passes the test, or -1 if none does.
JavaScript version:
ECMAScript 6
More examples
Example
Return the array index that matches a value greater than the number in the input box:
var
ages
=
[
4
,
12
,
16
,
20
]
;
function
checkAdult
(
age
)
{
return
age
=
document
.
getElementById
(
"
ageToCheck
"
)
.
value
;
}
function
myFunction
(
)
{
document
.
getElementById
(
"
demo
"
)
.
innerHTML
=
ages
.
findIndex
(
checkAdult
)
;
}
Try it »
JavaScript Array object