首页 前端知识 【JS】如何解决Cannot set properties of undefined

【JS】如何解决Cannot set properties of undefined

2024-01-27 01:01:57 前端知识 前端哥 1639 855 我要收藏

TypeError: Cannot set properties of undefined
类型错误:无法设置未定义的属性

问题解析

当前的是当前对象或者数组是undefined,但是却用来引用属性或者索引

比如下面两种情况

const value = undefined
value.a // TypeError: Cannot read properties of undefined (reading 'a')
value[0] // TypeError: Cannot read properties of undefined (reading '0')
复制

或者是当前的value值不是我们显式声明的undefined,而是运算之后得到undefined,之后我们再去用它

const value = {}
value.a.b // TypeError: Cannot read properties of undefined (reading 'b')
value.a // undefined
复制

解决方案

问题清楚了, 解决的方式就是不用undefined直接去应用对象,解决报错问题可以用以下方法

const value = undefined
//解决方法1: if条件
if(value){
value = {}
value.a
}
// 解决方法2:?运算符
value?.a
// 解决方法3:||运算符
const preValue = value || {}
preValue.a
复制
转载请注明出处或者链接地址:https://www.qianduange.cn//article/563.html
标签
评论
还可以输入200
共0条数据,当前/页
发布的文章

06-jquery函数

2024-02-06 15:02:47

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!