JavaScript Array find() 方法
实例
获取数组中第一个值为 18 或更大的元素的值:
var ages = [3, 10, 18, 20];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAdult);
}
定义和用法
find() 方法返回数组中第一个通过测试的元素的值(作为函数提供)。
find() 方法对数组中存在的每个元素执行一次函数:
- 如果找到函数返回 true 值的数组元素,则 find() 返回该数组元素的值(并且不检查剩余值)
- 否则返回 undefined
注释:find() 不对空数组执行该函数。
注释:find() 不会改变原始数组。
浏览器支持
注释:Internet Explorer 不支持 find() 方法。
语法
array.find(function(currentValue, index, arr), thisValue)
参数值
| 参数 | 描述 | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| function(currentValue, index, arr) | 必需。为数组中的每个元素运行的函数。
函数参数:
|
||||||||
| thisValue |
可选。要传递给函数以用作其 "this" 值的值。 如果此参数为空,则值 "undefined" 将作为其 "this" 值传递。 |
技术细节
| 返回值: | 如果数组中的任何元素通过测试,则返回数组元素值,否则返回 undefined。
|
| JavaScript 版本: | ECMAScript 6
|
|---|

免费 AI IDE

JavaScript Array 对象
更多建议: