在Javascript中创建具有自己的属性的对象数组

时间:2015-02-07 22:03:41

标签: javascript

var i;


    var Book = new Array();
    var Book[0] = [title: "1984", author: "George Orwell", publisher: "Harvill Secker", price: "€8.99"];
    var Book[1] = [title: "Metro 2033", author: "Dmitry Glukhovsky", publisher: "Orionbooks", price: "€12.99"];
    var Book[2] = [title: "Always Outnumbered, Always Outgunned", author: "Walter Mosley", publisher: "W. W. Norton & Company", price: "€5.99"];    
    var Book[3] = [title: "Journey to the Center of the Earth", author: "Jules Verne", publisher: "Pierre Jules Hetzel", price: "€4.99"];

我试图找出如何制作具有各自属性的对象数组,但这似乎并不起作用。我无法理解发生了什么。

编辑:

    var i;
    var Book = new Array();
    Book[0] = {title: "1984", author: "George Orwell", publisher: "Harvill Secker", price: "€8.99"};
    Book[1] = {title: "Metro 2033", author: "Dmitry Glukhovsky", publisher: "Orionbooks", price: "€12.99"};
    Book[2] = {title: "Always Outnumbered, Always Outgunned", author: "Walter Mosley", publisher: "W. W. Norton & Company", price: "€5.99"};    
    Book[3] = {title: "Journey to the Center of the Earth", author: "Jules Verne", publisher: "Pierre Jules Hetzel", price: "€4.99"};

    for (i = 0; i < 4; i++)
    {
        document.write("Book: " + Book[i].title + "Author: " + Book[i].author "Publisher: " + Book[i].publisher + "Price: " + Book[i].price);
    }

这是更新后的代码。这仍然无效。

编辑2:错过了#34; +&#34;在document.write中。

2 个答案:

答案 0 :(得分:2)

您正在将数组传递给数组,而不是对象。

  1. 更改[的{​​{1}},因为第二个是正确的对象定义。
  2. 不要使用var两次。一旦你有变量,就可以使用它而不用var。

    {
  3. 你可以像这样使用它:

    var Book = new Array();
    
    Book[0] = {title: "1984", author: "George Orwell", publisher: "Harvill Secker", price: "€8.99"};
    

答案 1 :(得分:0)

语法不正确。

数组是:[] 对象是:{}

除了Book变量必须声明一次。

正确的方法是:

 var Book = new Array();
 Book[0] = {title: "1984", author: "George Orwell", publisher: "Harvill Secker", price: "€8.99"};
 Book[1] = {itle: "Metro 2033", author: "Dmitry Glukhovsky", publisher: "Orionbooks", price: "€12.99"};
 Book[2] = {title: "Always Outnumbered, Always Outgunned", author: "Walter Mosley", publisher: "W. W. Norton & Company", price: "€5.99"};    
 Book[3] = {title: "Journey to the Center of the Earth", author: "Jules Verne", publisher: "Pierre Jules Hetzel", price: "€4.99"};

Book.push ( {title: "1984", author: "George Orwell", publisher: "Harvill Secker", price: "€8.99"}) 
//...