定义和用法
find() 方法返回通过测试(函数内判断)的数组的第一个元素的值。
find() 方法为数组中的每个元素都调用一次函数执行:
- 当数组中的元素在测试条件时返回 true 时,
find()返回符合条件的元素,之后的值不会再调用执行函数。 - 如果没有符合条件的元素返回 undefined
注意:
find()对于空数组,函数是不会执行的。find()并没有改变数组的原始值。
语法
array.find(function(currentValue, index, arr),thisValue)
参数
| 参数 | 描述 | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| function(currentValue, index,arr) | 必需。数组每个元素需要执行的函数。 函数参数:
|
||||||||
| thisValue | 可选。 传递给函数的值一般用 “this” 值。 如果这个参数为空, “undefined” 会传递给 “this” 值 |
浏览器支持
所有主流浏览器都支持find()方法。
注意: IE 11 及更早版本不支持 find() 方法。

实例 1
获取数组中年龄大于 18 的第一个元素:
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
var ages = [3, 10, 18, 20];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAdult);
}
</script>
实例 2
返回符合大于输入框中数字的数组索引值:
<p>点击按钮返回符合大于输入框中指定数字的数组元素。</p>
<p>最小年龄: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">点我</button>
<p>值: <span id="demo"></span></p>
<script>
var ages = [4, 12, 16, 20];
function checkAdult(age) {
return age >= document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAdult);
}
</script>