Array.prototype.find()未匹配时返回undefined,直接访问属性会报错;使用可选链操作符?.可安全访问,遇null/undefined自动短路返回undefined,并可与??配合提供默认值。

当使用 Array.prototype.find() 查找数组元素时,若未匹配到项会返回 undefined,直接访问其属性容易触发 Cannot read property 'xxx' of undefined 错误。配合可选链操作符 ?. 可安全、简洁地处理空值场景,避免冗余判断。
基础用法:避免运行时错误
find() 本身不保证返回对象,一旦结果为 undefined,后续点访问就会报错。可选链让属性访问“短路”——遇到 undefined 或 null 自动返回 undefined,不继续执行。
例如:
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
const user = users.find(u => u.id === 5); // undefined
console.log(user.name); // TypeError!
console.log(user?.name); // undefined(安全)
链式取值:多层嵌套安全访问
当目标字段是嵌套结构(如 user.profile.avatar.url),且整个查找结果可能为空时,可选链可逐级防护:
- 写法:
arr.find(...)?.profile?.avatar?.url - 效果:只要任意一环是
null或undefined,整体表达式立即返回undefined - 对比传统写法:
const u = arr.find(...); u && u.profile && u.profile.avatar && u.profile.avatar.url—— 冗长且易出错
配合空值合并 ?? 提供默认值
可选链常与空值合并操作符 ?? 搭配,为“找不到或字段缺失”提供兜底值:
users.find(u => u.id === 3)?.name ?? '未知用户'items.find(i => i.active)?.meta?.title ?? '暂无标题'- 注意:不要用
||替代??,否则0、''、false等 falsy 值也会被覆盖
注意事项与边界情况
-
find()返回的是元素本身,不是包装对象,所以?.直接作用于该值是合法的 - 如果数组为空或条件无匹配,
find()返回undefined,undefined?.xxx合法且返回undefined - 不适用于需要区分“未找到”和“找到但字段为
undefined”的场景(此时需额外判断find()结果是否严格等于undefined) - 确保运行环境支持可选链(Chrome 80+、Firefox 74+、Node.js 14.0+;TypeScript 3.7+)










