JavaScript - 数组 find() 方法
在 JavaScript 中,Array.find() 方法对每个数组元素执行回调函数,并检索数组中满足回调函数指定条件的第一个元素。
如果数组元素不满足特定条件,此方法将返回 undefined。它不会对空数组元素执行该函数。此方法不会更改原始数组。
findIndex() 和 find() 方法的区别在于:findIndex() 方法返回满足测试函数的元素的第一个索引位置(而不是元素值)。
语法
以下是 JavaScript 数组 find() 方法的语法 -
array.find(callbackFn (element, index, array), thisArg);
参数
此方法接受两个参数。具体描述如下 -
-
callbackfn - 这是一个回调函数,数组中的每个元素都会被调用一次。它还需要三个参数:
- element − 数组中当前正在处理的元素。
- index − 当前正在处理的元素的索引。
- array − 当前元素的数组。
- thisArg(可选)− 指定传递给函数的值,用作其 this 值。
返回值
此方法返回数组中满足所提供测试函数的第一个元素;否则,返回"undefined"。
示例
示例 1
在下面的示例中,我们使用 JavaScript 数组 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 作为输出,因为它是数组 elements 中第一个大于 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}

