JavaScript中的find方法,以及如何使用它来查找并返回给定数组中满足条件的第一个元素。如果找不到元素,它将返回未定义。
一、 JavaScript 数组 find() 方法
const names = ['Florin','Ivan','Liam'];
const res = names.find(findIvan)
function findIvan(item){
return item === 'Ivan';
}
console.log(res);
输出
const persons = [
{
name:'Florin',
age: 25,
},{
name:'Ivan',
age: 20,
},{
name:'Liam',
age: 18,
}
];
const res = persons.find(findFlorin)
function findFlorin(persons){
return persons.name === 'Florin';
}
console.log(res);
输出
JavaScript中find()
方法用于检索数组中满足指定条件的第一个元素。
Array find() 方法对数组中的每个元素执行一次提供的函数,直到找到该函数返回真值的元素。该 find()
方法不会改变原始数组。
二、 数组 find()语法:
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. |
2.1、 参数:
function(currentValue, index, arr)
: 对数组中的每个值执行的函数,直到找到满足条件的第一个元素。它需要三个参数:
参数名 | 注解 |
---|---|
currentValue | 数组中当前正在处理的元素。 |
index (可选) | 数组中当前正在处理的元素的索引。 |
arr (可选) | find() 调用了该数组。 |
thisValue (可选) | this 执行回调函数时使用的值。 |
三、JavaScript数组find()方法示例:
//在这里,find() 方法找到一个正数。
// Input array contain some elements.
let array = [-10, -0.20, 0.30, -40, -50];
// Method (return element > 0).
let found = array.find(function (element) {
return element > 0;
});
// Printing desired values.
console.log(found);
//Explanation:
//该代码搜索“array”中大于“20”的第一个元素。它使用“find()”方法迭代数组并返回满足条件的第一个元素。最后,它将结果 (`30`) 记录到控制台。
输出
在这里,每当我们需要获取数组中第一个满足所提供的测试方法的元素的值时,我们就使用 JavaScript中的
find()
方法。
// Input array contain some elements.
let array = [2, 7, 8, 9];
// Provided testing method (return element > 4).
let found = array.find(function (element) {
return element > 4;
});
// Printing desired values.
console.log(found);
//该代码的目的是找到“array”中第一个大于“4”的元素。它使用“find()”方法,迭代数组直到找到匹配的元素。它将结果 (`7`) 记录到控制台。
输出
3.0、数组查找方法:
Method | Finds |
---|---|
indexOf() | 具有指定值的第一个元素的索引 |
lastIndexOf() | 最后一个具有指定值的元素的索引 |
find() | 通过测试的第一个元素的值 |
findIndex() | 通过测试的第一个元素的索引 |
findLast() | 最后一个通过测试的元素的值 |
findLastIndex() | 最后一个通过测试的元素的索引 |
四、Example
Find the value of the first element 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>