find方法返回数组中第一个满足测试函数的元素,未找到时返回undefined;它不修改原数组,遍历到首个匹配项即停止,语法为array.find(callback, thisArg),callback需返回布尔值以判定匹配。

find 方法用于返回数组中第一个满足提供的测试函数的元素,如果没找到则返回 undefined。它不会修改原数组,且只遍历一次,遇到第一个匹配项就立即停止。
基本语法和用法
调用方式:array.find(callback(element[, index[, array]])[, thisArg])
-
callback是必需的测试函数,接收当前元素、索引、原数组三个参数,返回布尔值 - 只要回调函数返回
true,该元素就被视为“满足条件”,find立即返回它 - 没有匹配时返回
undefined,不是空数组或null
常见查找场景示例
查找数字数组中第一个大于 10 的数:
const numbers = [3, 8, 12, 15, 6]; const firstLarge = numbers.find(n => n > 10); // 12
查找对象数组中某个 id 对应的对象:
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const user = users.find(u => u.id === 2); // { id: 2, name: 'Bob' }
注意 null/undefined 和找不到的情况
因为 find 找不到时返回 undefined,直接访问属性可能报错(如 user.name):
- 安全写法:先判断是否存在,再取值,例如
user && user.name - 可选链操作符:用
user?.name(ES2020+) - 提供默认值:用逻辑运算符
(users.find(...) || {}).name
和 filter、findIndex 的区别
find 关注“第一个匹配的值”;filter 返回所有匹配项组成的数组;findIndex 返回第一个匹配项的索引(没找到返回 -1)。
别误用 filter(arr => condition)[0] 替代 find——前者会遍历整个数组,性能差,语义也不准确。


















