在 JavaScript 中,Array.find() 方法对每个数组元素执行回调函数,并检索数组中满足回调函数的指定条件的第一个元素。
如果数组元素不满足特定条件,则此方法返回 “undefined”。它不会为空数组元素执行函数。此方法不会更改原始数组。
findIndex() 和 find() 方法之间的区别在于; findIndex() 方法返回满足 testing 函数的元素的第一个索引位置(而不是元素值)。
语法
以下是 JavaScript Array.find() 方法的语法 -
array.find(callbackFn (element, index, array), thisArg);
参数
此方法接受两个参数。下面描述相同 -
- callbackFn − 这是一个回调函数,将为数组中的每个元素调用一次。它进一步需要三个参数:
- element − 数组中正在处理的当前元素。
- index − 正在处理的当前元素的索引。
- array− 当前元素的数组。
- thisArg(可选)- 它指定传递给函数的值,用作其 this 值。
返回值
此方法返回数组中满足提供的 testing 函数的第一个元素;否则为 'undefined'。
示例 1
在下面的示例中,我们使用 JavaScript Array.find() 方法在数组元素中定位大于 10 的第一个元素 -
<html>
<body>
<script>
const numbers = [10, 23, 12, 43, 68];
const result = numbers.find(function(element) {
return element > 10;
});
document.write(result);
</script>
</body>
</html>
输出
上述程序返回 23 作为输出,因为它是数组元素中第一个大于 10 的元素5。
23
示例 2
在这里,我们找到 “animals” 数组中长度大于 5 的第一个元素 -
<html>
<body>
<script>
const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"];
const result = animals.find(func => func.length > 5);
document.write(result);
</script>
</body>
</html>
输出
Cheetah
示例 3
在这里,我们将 find() 方法与对象数组一起使用,以选择玩家中的第一项(年龄大于 40)-
<html>
<body>
<script>
const players = [
{ name: 'Kohli', age: 35 },
{ name: 'Ponting', age: 48 },
{ name: 'Sachin', age: 50 }
];
const result = players.find(item => item.age > 40);
document.write(JSON.stringify(result));
</script>
</body>
</html>
输出
{"name":"Ponting","age":48}