JavaScript find()Method

Array 对象参考手册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); }

fruitsOutput:

18

Try it Yourself »

Definition and Usage

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

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

  • When the element in the array returns during the test conditiontrueWhen this happens, find() returns the matching element, and subsequent values will no longer call the execution function.
  • If there are no matching elements, undefined is returned.

Note:For an empty array, find() will 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

Parameter Description
function(currentValue, index,arr) Required. The function that needs to be executed for each element of the array.
Function parameters:
Parameter Description
currentValue Required. The current element
index Optional. The index value 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" will be passed to the "this" value.

Technical Details

Return value: Returns the value of the first array element that meets the test condition; if there is no matching element, returnsundefined。
JavaScript Version: ECMAScript 6

More Examples

Example

Returns 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 Yourself »

Array 对象参考手册JavaScript Array Object

Other Extensions