如何使用类语法将新书对象推入空数阵列中?
如果类声明中的构造函数已经创建了一个书对象,如果我正确地考虑了这一点,我需要做的就是实例化该对象,然后将该对象推入数组中。我在这里缺少什么?
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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如前所述,最初您没有将任何参数传递给推送方法。如果您想创建一系列数组,例如:
[
[
“书”,
“查理·莫顿”,
“ 500”,
真的
],,
[
“两本书”,
“查理·莫顿”,
“ 200”,
错误的
这是给
]
尽管我认为具有键的一系列对象:值配对将使使用量更易于使用。
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.