从对象列表中删除对象时出现未定义的错误。
html:
<div>
<p each="{holidayListSecondPart, i in this.holidayListSecondPart}">
<span id="{holidayListSecondPart.description}">{holidayListSecondPart.description}</span>
<span id="delete{i+1}" onclick="{remove}">delete</span>
<span id="editHoliday{i+1}" onclick="{editHoliday}">edit</span>
</p>
</div>
js代码:
remove(e){
e.target.parentNode.remove();
console.log('DataMixin.data before delete ', DataMixin.data.holidayList);
self.deletingId = e.target.parentNode.firstElementChild.id;
for(var i = 0; i<Object.keys(DataMixin.data.holidayList).length; i++){
if(self.deletingId == DataMixin.data.holidayList[i+1].reason){
console.log("delete ID matched: ", i+1);
console.log('ID to be deleted is: ' , DataMixin.data.holidayList[i+1]);
delete DataMixin.data.holidayList[i+1];
}
}
console.log('DataMixin.data after delete ', DataMixin.data.holidayList);
}
对象列表如下所示:
删除第一个对象后,我尝试删除第三个对象,其抛出错误:
Uncaught TypeError: Cannot read property 'reason' of undefined
我确信循环逻辑有些问题,但我无法理解它。我哪里做错了?
更新:
我正在尝试从 DOM 中删除一个元素,并在单击时从 Javascript 对象中删除它的属性,如下所示: