无法删除循环中的对象属性

时间:2016-09-15 13:48:02

标签: javascript jquery arrays javascript-objects

function remove(e){
    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('matched'); //prints on deletion of 5th object and then 3rd object as well
            delete DataMixin.data.holidayList[i+1];
            e.target.parentNode.remove();
            console.log('ID deleted is: ' , DataMixin.data.holidayList[i+1]); // still prints the value
        }
    }
}

在十个具有键/值对的对象中,我成功删除了第五个对象,然后删除第三个对象即使if条件满足也抛出错误:

此处出现错误:reason

未定义DataMixin.data.holidayList[i+1].reason

1 个答案:

答案 0 :(得分:0)

在我看来(Object.keys(DataMixin.data.holidayList)。length - 1)是DataMixin.data.holidayList中的最后一个属性键,所以如果你做DataMixin.data.holidayList [i + 1] ,在循环结束时,如果找不到对象属性。