Cannot read properties of undefined (reading '0')

2026年05月19日 19:50 10.22 秒 success

错误信息

Cannot read properties of undefined (reading '0')

AI 解决方案

🔍 错误分析

1. 🌐 错误翻译

原文:Cannot read properties of undefined (reading '0')
译文:无法读取未定义(undefined)的属性 '0'


2. 🎯 原因分析

根本原因: 代码试图访问一个值为 undefined 的变量的索引 0(通常是数组的第一个元素或字符串的第一个字符)。

常见场景:

场景示例
数组未初始化let arr; arr[0]
函数返回值为undefinedgetArray()[0]
解构赋值目标为空const [first] = undefined
对象属性不存在obj.data[0](data为undefined)

3. 💡 解决方案

方案一:可选链操作符(推荐)

// 安全访问嵌套属性
const value = myArray?.[0];
const value = obj?.data?.[0];

方案二:空值合并 + 默认值

const value = (myArray || [])[0] ?? '默认值';

方案三:提前校验

if (Array.isArray(myArray) && myArray.length > 0) {
    const value = myArray[0];
}

方案四:使用解构 + 默认值

const [first = '默认值'] = myArray || [];


4. 🛡️ 预防措施

  • 使用 TypeScript:类型检查可在编译阶段发现此类问题

  • ESLint 规则:启用 @typescript-eslint/no-unnecessary-condition 检测潜在的 undefined 访问