Reputation: 19
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"];
I'm trying to figure out how to make an array of objects that have their own properties but this doesn't seem to work. I can't understand what's going on.
EDIT:
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);
}
This is the updated code. This still doesn't work.
EDIT 2: Was missing a "+" in the document.write.
Upvotes: 0
Views: 48
Reputation: 21
The syntax is incorrect.
Array is: [ ] Object is: { }
Besides the Book variable must be declared once.
The correct way is :
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"};
Or
Book.push ( {title: "1984", author: "George Orwell", publisher: "Harvill Secker", price: "€8.99"})
//...
Upvotes: 0
Reputation: 1624
You are passing array to your arrays, not objects.
[
for {
, since second is proper object definition.Don't use var twice. Once you have variable, you can use it without var.
var Book = new Array();
Book[0] = {title: "1984", author: "George Orwell", publisher: "Harvill Secker", price: "€8.99"};
You can use it like this:
alert(Book[0].title);
Upvotes: 2