例如,我正在创建一个对象数组,该数组中的每个对象都应该描述一本书。
在我的脑海里,这是我所看到的:
var booksArray = ["Always Running", "Hatchet", "Autobiography of Malcolm X", "Che Guevara: A Revolutionary Life", "The Prince"];我还应该给出以下属性:
标题:作者: alreadyRead:(boolean)
SO..with说这就是我的代码看起来的样子,我不知道我是不是做对了,看看book1,book2等等是如何没有连接到数组的。
var booksListArray = ["Always Running", "Hatchet", "Autobiography of Malcolm X", "Che Guevara: A Revolutionary Life", "The Prince"];
var book1 = {
title: "Always Running",
author: "Luis J. Rodriguez",
alreadyRead: true
}
var boook2 = {
tite: "Hatchet",
author: "Gary Paulsen",
alreadyRead: true
}发布于 2017-06-22 12:33:24
您可以将book对象直接放入数组中:
var books = [
{ title: "Always Running", author: "Luis J. Rodriguez", alreadyRead: true },
{ title: "Hatchet", author: "Gary Paulsen", alreadyRead: true },
// etc
];请注意,当您进行缩放(如在中,拥有数十万个图书对象实例)时,如果您使用构造函数,则JavaScript引擎可以为具有相同属性的许多对象优化其内部内存(例如,通过不将属性名称与每个对象实例一起存储):
function Book(title, author, alreadyRead) {
this.title = title;
this.author = author;
this.alreadyRead = alreadyRead;
}你可以这样使用它:
var books = [
new Book( "Always Running", "Luis J. Rodriguez", true ),
new Book( "Hatchet", "Gary Paulsen", true ),
// etc
];发布于 2017-06-22 12:38:08
很简单..。您已经使用book1和book2创建了一个对象,只需像这样将它们放入数组中:
var booksListArray = [
{
title: "Always Running",
author: "Luis J. Rodriguez",
alreadyRead: true
},
{
tite: "Hatchet",
author: "Gary Paulsen",
alreadyRead: true
}
]然后,您可以像这样访问图书详细信息(示例将显示第一本图书的标题):
booksListArray[0].title发布于 2017-06-22 12:38:44
编辑:更新了代码,以显示已读和未读的书。
使用push()方法将对象插入到数组中。
var booksListArray = ["Always Running", "Hatchet", "Autobiography of Malcolm X", "Che Guevara: A Revolutionary Life", "The Prince"];
var book1 = {
title: "Always Running",
author: "Luis J. Rodriguez",
alreadyRead: true
}
var book2 = {
title: "Hatchet",
author: "Gary Paulsen",
alreadyRead: true
}
var books = [];
books.push(book1);
books.push(book2);
console.log(books);
books.forEach(function(book){
if(book.alreadyRead){
console.log('I have read ' + book.title + ' by ' + book.author);
} else {
console.log('I haven\'t read ' + book.title+ ' by ' + book.author);
}
});
https://stackoverflow.com/questions/44690171
复制相似问题