开发者问题收集

将书籍对象插入到书籍数组中

2020-12-07
707

我正在执行一项任务,我必须将一本书添加到书籍数组中。但我得到的不是书籍数组,而是一个空数组。

class BookList{
  constructor(){
    this.books = []
  }

  add(book){
    this.books.push(book)
  }
}

class Book{
  constructor(title, genre, author, read){
      this.title = title || "No Title"
      this.genre = genre || "No Genre"
      this.author = author || "No Author"
      this.read = read || false
      this.readDate = new Date(Date.now())
  }
}

let book1 = new Book('Title')

new BookList().add(book1)

let blist = new BookList()

console.log(blist)
1个回答

您已创建了一个新的 BookList(),但尚未存储它: new BookList().add(book1)

如果您将其分配给变量,它将起作用:

let book1 = new Book('Title')


let blist = new BookList();

blist.add(book1)

console.log(blist)
Peter
2020-12-07