简体   繁体   English

无法从本地存储上的 JSON 阵列中删除特定元素

[英]Cant remove specific element from JSON Array on local storage

I am trying learn java script from making some projects by watching tutorials.我正在尝试通过观看教程制作一些项目来学习 java 脚本。 In One of my projects when I try to delete a specific element from the local storage by using,在我的一个项目中,当我尝试通过使用从本地存储中删除特定元素时,

static removeBook(isbn) {
    const books = Store.getBooks();

    books.forEach((book, index) => {
      if (book.ISBN === isbn) {
        books.splice(index, 1);
      }
    });
  }

But it's doesn't seems to be working.但这似乎不起作用。 Here are the codes of book class and Store Class that I used to create this local storage file.这是我用来创建这个本地存储文件的 class 和 Store Class 的代码。

Book class: Represent a Book Book class:代表一本书

class Book {
  constructor(title, author, ISBN) {
    this.title = title;
    this.author = author;
    this.ISBN = ISBN;
  }
}

Store Class: Handles Storage存储 Class:处理存储

class Store {
  static getBooks() {
    let books;
    if (localStorage.getItem("books") === null) {
      books = [];
    } else {
      books = JSON.parse(localStorage.getItem("books"));
    }

    return books;
  }

  static addBooks(book) {
    const books = Store.getBooks();

    books.push(book);
    localStorage.setItem("books", JSON.stringify(books));
  }

  static removeBook(isbn) {
    const books = Store.getBooks();

    books.forEach((book, index) => {
      if (book.ISBN === isbn) {
        books.splice(index, 1);
      }
    });
  }
}

After removing the book update the books collection in local storage with localStorage.setItem()删除书籍后,使用localStorage.setItem()更新本地存储中的书籍集合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM