解决 Cannot read properties of undefined类型的报错

慈云数据 2024-03-23 技术支持 80 0

报错类型一般为两种

解决 Cannot read properties of undefined类型的报错
(图片来源网络,侵删)

对象类型

对象没有数据的时候为undefined 这个时候访问内部内容就会报错

解决 Cannot read properties of undefined类型的报错
(图片来源网络,侵删)

举个例子

正常情况 对象有值的时候

var obj={name:‘张三’,age:18}

#此时对象有数据访问不会报错

console.log(obj.name)

1

2

3

对象没值的时候

var obj={}

console.log(obj.name)

#就会报错 Uncaught SyntaxError: Unexpected token ‘.’

#表示空对象{}不能使用.

1

2

3

4

对象为undefined的时候

#本地数据为后端获取的 直接赋值 当res.data没值的时候undefined

this.myData=res.data

#当前值为undefined

console.log(this.myData.name)

#报以下错误

VM214:1 Uncaught TypeError: Cannot read properties of undefined (reading ‘name’)

at :1:11

1

2

3

4

5

6

7

解决办法

使用可选链操作符 ?.

就以上问题进行修复

obj?.name

this.myData=res?.data

数组类型

数据没有值时 数组[index] 数组下标获取值会报错 尤其是对链式结构使用数组下标一层一层获取数据

举个例子: this.data[0].children[0].children[0].children[0]

在这种情况下 如果中间某一个数组没有数据就会出现报错

VM322:1 Uncaught TypeError: Cannot read properties of undefined (reading ‘[0]’)

at :1:7

————————————————

版权声明:本文为CSDN博主「爱编程的梨清」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/nbsl_/article/details/127438683

微信扫一扫加客服

微信扫一扫加客服

点击启动AI问答
Draggable Icon