Find the value of the first element with a value over 18:
const ages = [3, 10, 18, 20];
function checkAge(age) {
return age > 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAge);
}
Try it Yourself »
The find()
method returns the value of the first element that passes a test.
The find()
method executes a function for each array element.
The find()
method returns undefined
if no elements are found.
The find()
method does not execute the function for empty elements.
The find()
method does not change the original array.
array.find(
function(currentValue, index, arr),thisValue)
function() | Required. A function to run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default undefined .A value passed to the function as its this value. |
Type | Description |
A value | The value of the first element that pass the test. Otherwise it returns undefined . |
Find the value of the first element that with a value above a specific number:
<p><input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const ages = [4, 12, 16, 20];
function checkAge(age) {
return age > document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAge);
}
</script>
Try it Yourself »
find()
is an ECMAScript6 (ES6) feature.
ES6 (JavaScript 2015) is supported in all modern browsers:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
find()
is not supported in Internet Explorer 11 (or earlier).
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!