第85章 查找元素

案例85:查找元素——find 与 findIndex 定位目标

本案例演示 TypeScript 中使用数组的 find 与 findIndex 方法定位目标元素,包括满足特定条件的对象查找、索引定位及未找到时的兜底处理。

设计思路

定义一个用户对象数组,分别使用 find 根据年龄条件返回第一个匹配的用户,使用 findIndex 根据姓名条件返回索引。重点展示 TypeScript 对回调参数的类型推断,以及 find 可能返回 undefined 时需要做的防御处理。

核心代码

interface User {
  id: number;
  name: string;
  age: number;
}

const users: User[] = [
  { id: 1, name: "张三", age: 25 },
  { id: 2, name: "李四", age: 30 },
  { id: 3, name: "王五", age: 25 },
  { id: 4, name: "赵六", age: 28 },
];

// find:返回第一个满足条件的元素
const targetUser = users.find(user => user.age === 25);
console.log("找到的用户:", targetUser);
// 注意:find 可能返回 undefined

// findIndex:返回第一个满足条件的索引
const targetIndex = users.findIndex(user => user.name === "李四");
console.log("李四的索引:", targetIndex);

// 未找到时的防御处理
const notFound = users.find(user => user.age > 100);
console.log("不存在的人:", notFound ?? "无匹配");

运行结果:找到第一个25岁的用户(张三);李四的索引为1;不存在的人显示“无匹配”。

验证方法

在 Node.js 或浏览器控制台运行,观察输出是否符合预期。也可将条件改为 age === 30 查看索引变化。

要点:findIndex 找不到时返回 -1,而非 undefined,注意区分。

注意:回调函数中若需访问 this,请使用普通函数而非箭头函数,否则 this 指向会出错。

成功:类型推断让回调参数自动获得 User 类型,无需显式标注,代码更简洁。