如何使用 Class 语法将新的 Book 对象推入空数组?
How can I push a new Book object into empty array using Class syntax?
如果 class 声明中的构造函数已经创建了一本书 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(){
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);
如前所述,最初您没有向 push 方法传递任何参数。如果您要创建一个数组数组,例如:
[
[
“一本书”,
“查理莫顿”,
"500",
真的
],
[
“两本书”,
“查理莫顿”,
"200",
错误的
]
]
尽管我认为具有 key:value 配对的对象数组会更易于使用。
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);
如果 class 声明中的构造函数已经创建了一本书 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(){
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);
如前所述,最初您没有向 push 方法传递任何参数。如果您要创建一个数组数组,例如:
[ [ “一本书”, “查理莫顿”, "500", 真的 ], [ “两本书”, “查理莫顿”, "200", 错误的 ] ]
尽管我认为具有 key:value 配对的对象数组会更易于使用。
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);