If a constructor in the class declaration already creates a book object, If i'm thinking about this correctly, all I would need to do is instantiate the object, then push that object into an array. What am I missing here?
class Book{
constructor(title, author, pages, hasRead, library=[]){
this.title = title
this.author = author
this.pages = pages
this.hasRead = hasRead
this.library = library
}
addBookToLibrary(){
return this.library.push();
}
}
//instantiate Book Object
let newBook = new Book();
//push the object into the empty array??
newBook.addBookToLibrary("A book", "Charlie Morton", "500", true);
console.log(newBook.library);
CodePudding user response:
As stated, originally you were not passing any arguments to your push method. If you are looking to create an array of arrays like:
[ [ "A book", "Charlie Morton", "500", true ], [ "Two book", "Charlie Morton", "200", false ] ]
Though I think an array of objects with key:value pairing would make it easier to use.
class Book{
constructor(title, author, pages, hasRead, library=[]){
this.title = title
this.author = author
this.pages = pages
this.hasRead = hasRead
this.library = library
}
addBookToLibrary(book){
return this.library.push(book);
}
}
//instantiate Book Object
const newBook = new Book();
//push the object into the empty array??
newBook.addBookToLibrary(["A book", "Charlie Morton", "500", true]);
newBook.addBookToLibrary(["Two book", "Charlie Morton", "200", false]);
console.log(newBook.library);
CodePudding user response:
addBookToLibrary
need book
argument and then push book
object
class Book{
constructor(title, author, pages, hasRead, library=[]){
this.title = title
this.author = author
this.pages = pages
this.hasRead = hasRead
this.library = library
}
addBookToLibrary(book){
return this.library.push(book);
}
}
//instantiate Book Object
let newBook = new Book();
//push the object into the empty array??
newBook.addBookToLibrary("A book", "Charlie Morton", "500", true);
console.log(newBook.library);