find方法返回数组中第一个满足条件的元素,未找到则返回undefined;接收判断函数作为参数,支持索引和原数组传参,不修改原数组,常用于对象数组查找及安全访问。

find 是 JavaScript 数组的内置方法,用于查找并返回数组中第一个满足条件的元素;如果没找到,返回 undefined。
基本用法:传入一个判断函数
语法是 array.find(callback(element[, index[, array]])[, thisArg])。最常用的是第一个参数——一个返回布尔值的回调函数:
- 回调函数接收当前元素(必填),也可选接收索引和原数组
- 只要回调返回
true,find就立刻停止遍历,返回该元素 - 不会修改原数组
例如:
const numbers = [10, 25, 3, 48, 7];const firstBig = numbers.find(n => n > 20); // 返回 25
查找对象数组中的特定对象
这是常见场景。注意:返回的是原对象的引用,不是拷贝:
立即学习“Java免费学习笔记(深入)”;
const users = [{ id: 1, name: 'Alice', active: true },
{ id: 2, name: 'Bob', active: false },
{ id: 3, name: 'Charlie', active: true }
];
const activeUser = users.find(u => u.active && u.name.startsWith('A')); // { id: 1, name: 'Alice', active: true }
找不到时返回 undefined,记得做安全判断
find 不会抛错,但返回 undefined,直接访问属性容易报 Cannot read property of undefined:
- 用可选链操作符
?.:result?.name - 或提前判断:
if (result) { ... } - 需要默认值可用
??:(arr.find(...)) ?? defaultValue
和 findIndex、filter 的区别
别和类似方法混淆:
-
findIndex:返回匹配元素的索引(没找到返回-1) -
filter:返回所有匹配元素组成的新数组,哪怕只有一项也返回数组 -
find:只关心第一个命中项,适合“找一个代表”或“是否存在”的场景


















