You need to enable JavaScript to run this app. JS赋值countryCallingCode报ReferenceError未定义如何解决
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 09:09:00