javascript 为对象中的二级元素赋值 1006 Uncaught TypeError: Cannot set property ‘‘of undefined

tech2022-12-06  96

在js中,对于一个对象,我们为其二级元素进行赋值,可能会出现提示二级元素没有被定义。

比如:

certificate.accounting_entries[0].name = 'xxx'

certificate是一个对象,accounting_entries是其中的一个数组类型元素,赋值时不确定是否存在下标为0的数组子元素。

解决方案:

var temp_accounting_entry = {} if(certificate.accounting_entries[0] != undefined){ temp_accounting_entry = certificate.accounting_entries[0]; } temp_accounting_entry.name = 'xxx'; certificate.accounting_entries[0] = temp_accounting_entry;

 

软件工程小施同学 认证博客专家 学堂在线讲师 每一个伟大,都源于一个勇敢的开始(微博:“软件工程小施同学”,公号”微程序学堂“)
最新回复(0)