find 方法的用法
find 方法用于在数组中查找符合条件的第一个元素,如果找到则返回该元素,否则返回 undefined。
语法
js
复制
编辑
array.find(callback(element, index, array), thisArg);
callback:用于测试数组元素的函数,接收三个参数:
element:当前遍历的元素
index(可选):当前元素的索引
array(可选):正在遍历的数组
thisArg(可选):指定 callback 里的 this 指向
🚀 示例 1:查找符合条件的对象
js
复制
编辑
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" },
];
const result = users.find(user => user.id === 2);
console.log(result); // 输出: { id: 2, name: "Bob" }
✅ find 找到了 id === 2 的用户并返回该对象。
🚀 示例 2:在数组中查找数值
js
复制
编辑
const numbers = [10, 20, 30, 40, 50];
const found = numbers.find(num => num > 25);
console.log(found); // 输出: 30
✅ find 只返回第一个满足 num > 25 的值(30),而不会继续查找 40 和 50。
🚀 示例 3:找不到时返回 undefined
js
复制
编辑
const items = [{ id: 1, name: "Apple" }, { id: 2, name: "Banana" }];
const result = items.find(item => item.id === 3);
console.log(result); // 输出: undefined
✅ find 找不到 id === 3 的对象,所以返回 undefined。