【JS】如何解决Cannot set properties of undefined
•
前端
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://net2asp.com/95ffec448d.html
