簡體   English   中英

從數組中刪除特定元素-JavaScript

[英]Delete specific element from array - javascript

我想創建一個小程序,在其中輸入``書名''和isbn代碼以及其他內容,在我想創建一個提示詢問我要刪除哪本書(通過ISBN)之前,它工作得很好。 實際上工作正常; 當我寫我以陣列形式存儲的書的isbn時,它將刪除該書,它就是isbn,但是警報通知我該書不存在於我已存儲的每一本書的數據庫中(之前未添加)。

例如,我存儲了5本書,其中一本書是(數組中的第4個對象)帶有“ 12121” ISBN代碼,我想從數組中刪除該本書。 函數對數組中的前3個對象返回false(alert(“在我們的數據庫中不存在帶有該ISBN的書。”)),然后對第四個對象返回true,然后對其中的最后一個對象返回false。數組。

如何制作僅選擇(然后刪除)帶有ISBN的對象的函數,該對象放在提示框中,而無需檢查數組中的每個對象?

    var book = [];
book.push({
    bookName: "GameOfThrones",
    isbn: "12345",
});
function deleteBook(){
    var book1 = prompt("Enter the ISBN of the book you want to delete");
    for var(i=0; i<book.length; i++){
        if (book[i].isbn == book1){
            book.splice(i, 1);
            alert("Book is successfully deleted");
        }
        else{
            alert("Book with that ISBN doesn't exist in our database.");
        }
    }
    for (var i=0; i<book.length; i++){
        document.write(book[i].isbn + " - " + book[i].bookName + "<br/>");
    }
}

如果您選擇隨機使用元素數組,那么遍歷每個元素將無處可尋。 您的另一個選擇是使用哈希圖或對數組進行排序,然后使用二進制搜索算法。 就個人而言,除非您的Array非常大(十萬個元素的數量級),否則我不會為這樣的過早優化而煩惱。

順便說一句,如果您使用Array過濾器功能,則可以以更簡潔的方式編寫原始代碼。

    var books = [];
    books.push({
        bookName: "GameOfThrones",
        isbn: "12345",
    });

    var ISBNToDelete = prompt("Enter the ISBN of the book you want to delete");

    function deleteBookByISBN(isbn, books) {
        var newBooks = books.filter(function(book) {
           return book.isbn !== isbn;
        });
        if (newBooks.length != books.length) {
             alert("Book successfully deleted")  
        } else {
             alert("Book with that ISBN doesn't exist in our database.");
        }
        return newBooks;
    }
    books = deleteBookByISBN(ISBNToDelete, books); // reassign the new set of books to books.

您的示例最簡單的方法是找到項目后,使用break語句停止處理for循環:

 function deleteBook(){
     var book1 = prompt("Enter the ISBN of the book you want to delete");
     for (var i=0,count=book.length; i<count; i++){
         if (book[i].isbn == book1){
             book.splice(i, 1);
             alert("Book is successfully deleted");
             break;
         }
         else{
             alert("Book with that ISBN doesn't exist in our database.");
         }
     }
     for (var i=0; i<book.length; i++){
         document.write(book[i].isbn + " - " + book[i].bookName + "<br/>");
     } 
}

我不知道您要定位的瀏覽器,但是如果不是IE,則可以消除for循環並改用Array.findIndexhttps : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/參考/ Global_Objects / Array / findIndex

就像是:

var index = book.findIndex(function (element) { return element.isbn == book1 });

找到書后,您可以簡單地從for語句返回。 問題是當書在數組的末尾時,在這種情況下,您無論如何都要遍歷整個數組。

排序數組可以為您提供一些幫助(您大概會知道在哪里找書),但是最好的辦法是拋開數組並選擇某種哈希表。

容易實現的是:

var books = {};
books['UniqueISBN'] = {name: "Where is the sun", author: "Unknown"};

然后,您可以使用delete直接將其刪除;

var id = 'UniqueISBN';
delete books[id];

如果您對數組進行filter ,則可以返回所有不匹配的書。 在此過程中,如果找到了書,則可以存儲一個布爾值。 使用該布爾值,您可以執行其他操作(例如,從數據庫中刪除它)。

您可以在filter執行這些數據庫操作,但是為了使代碼更易於跟蹤和維護,最好將它們分開。 這就是為什么在filter之后有一個if -block的原因。

下面的示例演示了上述概念。 與控制台相反,它也使用textarea進行日志記錄。 這旨在作為演示如何使用textContent屬性輸出到HTML元素。

例:

 document.addEventListener("DOMContentLoaded", onLoad); var books = [{ bookName: "GameOfThrones", isbn: "12345" }, { bookName: "Jurrasic Park", isbn: "98765" }, { bookName: "Westworld", isbn: "33333" }]; function deleteBook(isbn) { // use isbn passed in, or look it up isbn = isbn || document.getElementById('isbn').value; var book_found = false; books = books.filter((book, i) => { if (book.isbn == isbn) { book_found = true; debug.textContent += `Deleting "${book.bookName} from database...\\n`; return false; } else return isbn != book.isbn; }); // handle any follow-up actions if (book_found) { debug.textContent += `New List (w/o ${isbn}):\\n`; outputBooks(books); } else debug.textContent += `Book (isnb:${isbn}) could not be found!\\n\\n`; } // Used for Logging Output (in place of console) function outputBooks(books) { books.forEach(book => { debug.textContent += [' ' + book.isbn, book.bookName].join(': ') + '\\n' }); debug.textContent += '\\n'; } // Ensures the debug element is on the page function onLoad(event) { // Default window.debug = document.getElementById('debug'); debug.textContent += 'Starting List:\\n'; outputBooks(books); } 
 textarea { height: 20em; width: 80%; display: block; } .block { display: block; } 
 <label>ISBN: <input id="isbn" type="text" /> </label> <button type="button" class="delete" onclick="deleteBook()">Delete</button> <label><span class="block">Debug:</span> <textarea id="debug" disabled></textarea> </label> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM