find方法返回数组中第一个满足条件的元素,否则返回undefined;它不改变原数组,找到后立即停止遍历,适合高效获取单个匹配项。
find 是 JavaScript 数组的一个内置方法,用于查找数组中第一个满足条件的元素,并返回该元素。如果没有找到符合条件的元素,则返回 undefined。
回调函数应返回一个布尔值,当返回 true 时
,find 方法立即返回当前元素。
查找数组中第一个大于 10 的数字:
const numbers = [5, 8, 12, 18, 3]; const result = numbers.find(num => num > 10); // result: 12查找对象数组中符合特定条件的对象:
const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' } ];const user = users.find(u => u.id === 2); // user: { id: 2, name: 'Bob' }
基本上就这些。find 方法适合在需要根据条件获取单个元素时使用,比 filter 更高效,因为它不会遍历整个数组。