从对象列表中删除对象时出现未定义的错误。
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 code:
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
我确信循环逻辑有些问题,但我无法理解它。我哪里出错了?
更新:
我试图从点击下面的Javascript对象中删除DOM中的元素及其属性:
答案 0 :(得分:1)
如果从DataMixin.data.holidayList中删除对象,则无法再次从0索引到Object.keys(DataMixin.data.holidayList).length运行对象。因为你删除了它的一个字段(让我们说索引为3的对象),当函数执行此部分时:
for (var property in DataMixin.data.holidayList){
if (DataMixin.data.holidayList.hasOwnProperty(property)){
//put your code for each property here
}
}
你将无法阅读财产&#39;原因&#39;未定义的错误,导致您删除此字段。你应该用这个:
Object.keys(obj).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object
});
或者您可以使用此方法:
DataGridView