1.核心特点
- 查找单个元素:返回数组中第一个满足测试函数的元素值(不是数组)。
- 不修改原数组:原数组保持不变。
- 必须返回布尔值:回调函数应返回
true(找到元素并返回)或 false(继续查找),一旦返回true,查找立即停止。
- 可中途退出:一旦找到符合条件的第一个元素,立即终止循环。
- 空数组处理:若原数组为空,返回
undefined。
2.语法
const foundElement = arr.find(function(value, index, array) {
// 测试条件
return condition; // 当条件为true时,返回当前元素并停止遍历
}, thisArg);
参数说明
value:当前处理的元素(必选)。
index:当前元素的索引(可选)。
array:原数组本身(可选)。
thisArg:回调函数中 this 的指向(可选,通常很少使用)。
3.示例
3.1 查找数值(简单条件)
const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(num => num > 10);
console.log(found); // 输出: 12(第一个大于10的元素)
3.2 查找对象数组中的元素
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 17 },
{ name: 'Charlie', age: 30 }
];
const adult = users.find(user => user.age >= 18);
console.log(adult); // 输出: { name: 'Alice', age: 25 }(第一个成年人)
3.3 使用索引辅助查找
const arr = ['a', 'b', 'c', 'd'];
// 查找索引为偶数的第一个元素,且元素值不为'b'
const result = arr.find((value, index) => {
return index % 2 === 0 && value !== 'b';
});
console.log(result); // 输出: 'a'(第一个满足条件的元素)
3.4 未找到元素时返回undefined
const numbers = [1, 2, 3];
const found = numbers.find(num => num > 5);
console.log(found); // 输出: undefined
4.注意事项
4.1回调函数需返回布尔值
- 若返回非布尔值,会隐式转换为布尔值(如
0、""、null 视为 false)。
- 一旦回调函数返回
true,立即返回当前元素并停止遍历。
4.2引用类型的返回
- 若找到的是对象,则返回的是原数组中该对象的引用(修改会同步):
const original = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];
const found = original.find(item => item.id === 1);
found.name = 'Updated';
console.log(original[0].name); // 输出: 'Updated'(原数组被修改)
4.3处理稀疏数组
- 空位(如
[1, , 3])会被跳过,回调函数不会执行:
const sparseArr = [1, , 3];
const result = sparseArr.find(() => true); // 第一个元素1已经满足条件(回调返回true),所以返回1
console.log(result); // 输出: 1
5.总结
- 适用场景:需要查找数组中第一个符合条件的元素(如用户ID匹配、第一个满足条件的选项)。
- 性能优势:找到第一个匹配项后立即停止,适合大型数组。
- 替代方案:
- 若需要所有符合条件的元素,使用
filter。
- 若需要元素的索引,使用
findIndex。
- 若需要判断数组中是否存在某元素,使用
includes(仅适用于基本类型,不适用条件查找)。