I recently developed a small program that allows users to enter the name of a book along with its ISBN code. Everything was working perfectly until I added a feature to delete books based on their ISBN. While the deletion process works fine, I noticed that the alert message incorrectly states that the book does not exist in the database for every book stored.
For instance, if I have 5 books saved and I try to delete the one with the ISBN "12121" (which is the 4th object in the array), the function first returns false for the first 3 objects, then true for the 4th object, and finally false for the last object in the array.
Is there a way to modify the function so it only targets the object with the specified ISBN without checking each entry in the array?
var books = [];
books.push({
bookName: "GameOfThrones",
isbn: "12345",
});
function deleteBook(){
var bookToDelete = prompt("Enter the ISBN of the book you want to delete");
for(var i=0; i<books.length; i++){
if (books[i].isbn == bookToDelete){
books.splice(i, 1);
alert("The book has been successfully deleted");
break;
}
}
for (var i=0; i<books.length; i++){
document.write(books[i].isbn + " - " + books[i].bookName + "<br/>");
}
}