You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何使用JavaScript可选链(?.)仍出现"undefined has no properties"错误?

解决可选链操作符(?.)访问属性时的"undefined has no properties"错误

当result = {}时,你的可选链写法会触发错误,核心原因是数组索引访问没有被可选链保护:

  • result?.records会返回undefined(因为空对象里没有records属性)
  • 后续执行undefined[0]时,直接访问了undefined的索引,没有用?.做保护,因此抛出"undefined has no properties"错误

而原&&判断能正常工作,是因为它在访问result.records.length前,先验证了result.records的存在性,避免了无效访问。

修正方案

给数组索引的访问也加上可选链,确保每一步属性/索引访问都被保护,同时可以省略冗余的result &&(可选链本身会处理result为null/undefined的情况)。

写法一:完整保护每一步访问

const result = {}; // 测试场景

if (result?.records?.[0]?.["sf_Level Two ID"]) {
  const getLatestDACCodesID = result?.records?.[0]?.["sf_Level Two ID"];
  console.log('getLatestDACCodesID ', getLatestDACCodesID);
}

每一步访问都通过?.保护:

  1. result?.records:若result不存在,直接返回undefined
  2. ?.[0]:若records不是数组/不存在,直接返回undefined
  3. ?.["sf_Level Two ID"]:若数组第0项不存在,直接返回undefined

写法二:和原&&逻辑完全等价(更简洁)

如果需要严格匹配原逻辑(确保records是有长度的数组),可以直接判断数组长度:

const result = {}; // 测试场景

if (result?.records?.length > 0) {
  const getLatestDACCodesID = result.records[0]["sf_Level Two ID"];
  console.log('getLatestDACCodesID ', getLatestDACCodesID);
}

这里result?.records?.length已经确保了records是存在且有内容的数组,后续直接访问索引不会触发错误。

内容的提问来源于stack exchange,提问作者Karim Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 10:05:32