【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

猜你喜欢

转载自blog.csdn.net/qq_41536505/article/details/129589514