例如,我正在创建一个对象数组,该数组中的每个对象都应该描述一本书。
在我的脑海中,这就是我所看到的:
var booksArray = ["Always Running", "Hatchet", "Autobiography of Malcolm X", "Che Guevara: A Revolutionary Life", "The Prince"];
我还应该提供以下属性:
标题: 作者: 已读:( bool 值)
所以..话虽如此,这就是我的代码的样子,我不知道我的做法是否正确,看看 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
}
最佳答案
您可以将 book
对象直接放入数组中:
var books = [
{ title: "Always Running", author: "Luis J. Rodriguez", alreadyRead: true },
{ title: "Hatchet", author: "Gary Paulsen", alreadyRead: true },
// etc
];
请注意,当您进行扩展时(例如,拥有数十万个 Book 对象实例),如果您使用构造函数,则 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
];
关于javascript - 如何赋予数组中的对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44690171/