0

从对象列表中删除对象时出现未定义的错误。

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 对象中删除它的属性,如下所示:

在此处输入图像描述

4

1 回答 1

1

如果从 DataMixin.data.holidayList 中删除对象,则无法再次从 0 索引到 Object.keys(DataMixin.data.holidayList).length 运行对象。因为您删除了它的一个字段(让我们说索引为 3 的对象),当函数将执行此部分时:

//i == 3
if(self.deletingId == DataMixin.data.holidayList[i+1].reason){
        //code
}

您将收到无法读取未定义错误的属性“原因”,因为您删除了此字段。你应该使用这个:

for (var property in DataMixin.data.holidayList){
  if (DataMixin.data.holidayList.hasOwnProperty(property)){
    //put your code for each property here
  }
}

或者你可以使用这个方法:

Object.keys(obj).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object 
});
于 2018-05-31T08:55:19.653 回答