[英]Error while deleting object in javascript
I get undefined error while deleting object from list of objects. 从对象列表删除对象时出现未定义错误。
Html: 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: 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);
}
List of object looks like this: 对象列表如下所示:
After deleting the first object, I try to delete third object its throwing error: 删除第一个对象后,我尝试删除第三个对象的抛出错误:
Uncaught TypeError: Cannot read property 'reason' of undefined
I am sure some thing wrong with looping logic but I am not able to get my head around it. 我确定循环逻辑有些问题,但是我无法回避它。 Where did I go wrong?
我哪里做错了?
Update: 更新:
I am trying to delete an element from DOM and its property from Javascript object on click like below: 我正在尝试从DOM上删除元素,并从Javascript对象上删除其属性,如下所示:
If you deleting objects from your DataMixin.data.holidayList, you cannot run through an object from 0 index to Object.keys(DataMixin.data.holidayList).length again. 如果从DataMixin.data.holidayList中删除对象,则无法再次运行从0索引到Object.keys(DataMixin.data.holidayList).length的对象。 Because you deleted one of its fields (lets say object with index 3), when function will do this part:
因为您删除了它的一个字段(比如说索引为3的对象),所以当函数执行此操作时:
//i == 3
if(self.deletingId == DataMixin.data.holidayList[i+1].reason){
//code
}
You will get Cannot read property 'reason' of undefined error, cause you deleted this field. 您将得到无法读取未定义错误的属性“原因”,因为您删除了此字段。 You should use this:
您应该使用此:
for (var property in DataMixin.data.holidayList){
if (DataMixin.data.holidayList.hasOwnProperty(property)){
//put your code for each property here
}
}
Or you can use this method: 或者您可以使用以下方法:
Object.keys(obj).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.