如何在Javascript中向数组添加其他对象

时间:2015-03-16 00:06:27

标签: javascript arrays javascript-objects

我希望学习如何在我创建的构造函数之后将对象添加到具有多个现有对象的数组。

//constructor function
function Bookdes(title, author, pages, current_page, available){
    this.title = title;
    this.author = author;
    this.pages = pages;
    this.current_page = current_page;
    this.available = available;
}
//array of books
var bookarrays = [
    new Bookdes("Fast Cars", "John Burns", 205, 43, "true"),
    new Bookdes("Slow Cars", "Joe Fast", 70, 32, "false" ),
    new Bookdes("Big Cars", "Darla Jean", 234, 42, "true"),
    new Bookdes("Small Cars", "Dema Jones", 214, 34, "false"),
    new Bookdes("Cars", "Alex Best", 235, 41, "true")
];

//Add two more books
bookarrays.push("Gasoline Car", "Johnny Walker", 200, 31, "true");
bookarrays.push("Natural gas car", "James Dean", 150, 21, "true");
console.log(bookarrays);

感谢,

1 个答案:

答案 0 :(得分:6)

问题是你没有调用构造函数。正确的电话是:

bookarrays.push(new Bookdes("Gasoline Car", "Johnny Walker", 200, 31, "true"));
相关问题