Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript find() Method

JavaScript find() Method

Array Object Reference JavaScript Array object

Example

Get the first element in the array whose age is greater than 18

var

ages

=

[

3

,

10

,

18

,

20

]

;

function

checkAdult

(

age

)

{

return

age

=

18

;

}

function

myFunction

(

)

{

document

.

getElementById

(

"

demo

"

)

.

innerHTML

=

ages

.

find

(

checkAdult

)

;

}

fruits Output result:

18

Try it »


Definition and Usage

The find() method returns the value of the first element in an array that passes the test (determined by the function).

The find() method calls a function once for each element in the array:

Note: For an empty array, find() does not execute the function.

Note: find() 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
find() 45.0 12.0 25.0 7.1 32.0

Note: IE 11 and earlier versions do not support the find() method.


Syntax


array.find(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 value of the first array element that passes the test, or undefined if none does.
JavaScript version: ECMAScript 6

More examples

Example

Return the array index value that is 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

.

find

(

checkAdult

)

;

}

Try it »


Array Object Reference JavaScript Array object