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
}
}
}
出與鍵/值對10個的對象,我成功刪除第五對象的對象屬性,然後刪除第三個目標是拋出錯誤:無法刪除在一個循環
錯誤在這裏:reason
在DataMixin.data.holidayList[i+1].reason
你是否意識到,當你刪除一個條目數組縮短(因此你可能會嘗試訪問一個不存在的索引)? – FDavidov
對數組項目的'delete'將該項目設置爲'未定義',它不會將其從數組中移除。這就是說,我迷失了你的邏輯,試圖刪除'i + 1'。 MCVE肯定會有所幫助。也許你應該以相反的順序迭代 –
@FDavidov我打算使用'onclick'去除函數,它應該在循環內設置'i'值爲0? – Satyadev