JS赋值countryCallingCode报ReferenceError未定义如何解决
问题原因
你尝试直接为多层嵌套的不存在属性赋值时,JS会先读取this.allData.customerFacingPhone,该属性初始值为undefined,对undefined追加子属性就会抛出引用错误,需要先将上层customerFacingPhone初始化为对象类型,再给下层countryCallingCode赋值。
可行实现方案
- 方案1:手动判断初始化(兼容性最优,支持所有JS运行环境)
// 先判断父级属性是否存在,不存在则初始化为空对象 if (!this.allData.customerFacingPhone) { this.allData.customerFacingPhone = {} } // 再完成目标属性赋值 this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode
- 方案2:简洁语法实现(ES2021+支持,现代浏览器、Node.js 15及以上版本均可使用)
// 逻辑或赋值运算符,父级属性为空时自动初始化空对象 this.allData.customerFacingPhone ||= {} this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode
- 方案3:合并赋值(适合需要同时为
customerFacingPhone设置多个属性的场景)
this.allData.customerFacingPhone = Object.assign({}, this.allData.customerFacingPhone, { countryCallingCode: newItem.countryCallingCode })
内容的提问来源于stack exchange,提问作者Mayroy
相关产品推荐
相关产品推荐

