如何修复按标题从数组中删除对象的功能异常问题?
Hey there! Let's fix that pesky deleteItem function for you. Your addItem works fine, but the delete logic has a common bug that's keeping it from running correctly.
问题根源
The issue is in how you're using a forward for loop with splice. When you delete an element with splice(i, 1), the array length shrinks by 1 immediately. But your loop variable i keeps incrementing, which means you'll skip over the next element in the array.
For example:
- If your array is
[{title: "Wood"}, {title: "Nails"}, {title: "Wood"}] - When
i=0you delete the first "Wood", the array becomes[{title: "Nails"}, {title: "Wood"}] - Then
iincrements to 1, and you check the second element (original third element), completely skipping over "Nails"
Another small thing: you're not clearing this.item.title after deletion, which could lead to accidental repeated deletions later.
修复方案
Option 1: Loop in reverse (great for deleting single/multiple matches)
By looping from the end of the array to the start, deleting elements won't mess up the positions of the elements you haven't checked yet:
deleteItem() { console.log("ID ARTIKLA: ", this.item.title); // Loop backwards to avoid skipping elements for (let i = this.ListOfUsedMaterials.length - 1; i >= 0; i--) { if (this.ListOfUsedMaterials[i].title === this.item.title) { this.ListOfUsedMaterials.splice(i, 1); // Add a break here if you only want to delete the first matching item // break; } } // Clear the input to prevent accidental repeats this.item.title = ""; }
Option 2: Use filter (cleaner for deleting all matches)
The filter method creates a new array with all elements that pass your test—this is more concise and avoids loop-related bugs entirely:
deleteItem() { console.log("ID ARTIKLA: ", this.item.title); // Keep only items that don't match the target title this.ListOfUsedMaterials = this.ListOfUsedMaterials.filter(item => { return item.title !== this.item.title; }); // Clear the input field this.item.title = ""; }
Quick note: Use Option 1 if you only need to delete the first matching item. Use Option 2 if you want to remove every item with that title—it's much cleaner!
Extra Tips
- Always use
===(strict equality) instead of==to avoid unexpected type conversion issues - Clearing
this.item.titleafter deletion prevents users from accidentally deleting the same item again without retyping
内容的提问来源于stack exchange,提问作者Pero Peric

