在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;