find方法返回数组中第一个满足条件的元素,未找到时返回undefined;它不修改原数组,只遍历至首个匹配项即停止,区别于findIndex(返回索引)和filter(返回所有匹配项数组)。

find 是 JavaScript 数组的内置方法,用于查找并返回数组中第一个满足条件的元素;如果没找到,返回 undefined。
基本用法:传入一个判断函数
语法:array.find(callback(element[, index[, array]])[, thisArg])
核心是传入一个回调函数,它接收当前元素(必选),可选地接收索引和原数组。只要回调函数对某个元素返回 true,find 就立刻停止遍历,返回该元素。
- 只返回第一个匹配项,不会继续往后找
- 不改变原数组
- 找不到时返回
undefined,不是空数组或null
常见使用示例
比如有一个用户列表:
立即学习“Java免费学习笔记(深入)”;
将一个或多个视频上传至YouTube。当用户想“上传到YouTube”“发YouTube”“批量上传”“upload to YouTube”“post videos to YouTube”或发布到YouTube时使用此技能。
const users = [
{ id: 1, name: 'Alice', active: true },
{ id: 2, name: 'Bob', active: false },
{ id: 3, name: 'Charlie', active: true }
];
查找第一个活跃用户:
const firstActive = users.find(user => user.active);
// → { id: 1, name: 'Alice', active: true }
查找 id 为 2 的用户:
const user2 = users.find(u => u.id === 2);
// → { id: 2, name: 'Bob', active: false }
注意点:与 findIndex、filter 的区别
find 返回的是元素本身;findIndex 返回的是该元素的下标(没找到返回 -1);filter 返回所有匹配项组成的新数组(即使只有一项,也是数组)。
- 要取值 → 用
find - 要改原数组某一项 → 先
findIndex得到位置,再赋值 - 要多个结果 → 用
filter
安全使用建议
因为没找到时返回 undefined,直接访问属性可能报错(如 firstActive.name)。建议:
- 先判断是否存在:
if (firstActive) { ... } - 用可选链操作符(ES2020+):
firstActive?.name - 提供默认值:
const name = (firstActive || {}).name;

















