Beginner JavaScript help

Rage187

Lifer
Dec 30, 2000
14,276
4
81
var books = [ "Moby Dick", "Jane Eyre", "The Bible" ]
var books[0] = {title: "Moby Dick", author: "Melville"}
var books[1] = {title: "Jane Eyre", author: "Bronte"}
var books[2] = {title: "The Bible", author: "Steve"}

printp(books[0].title, " is by ", books[0].author)
printp(books[1].title, " is by ", books[1].author)
printp(books[2].title, " is by ", books[2].author)

books[0]["rating"] = 10

print(books[0])

Get an error that I am missing syntax before line 2. I have tried commas, colons, semicolons, brackets, paranthesis. to no avail.
 

clamum

Lifer
Feb 13, 2003
26,256
406
126
That is incorrect syntax for an array.

You would have to do something like this:
var books = new Array();
books[0] = "title: 'Moby Dick', author: 'Melville'";
books[1] = "title: 'Jane Eyre', author: 'Bronte'";

and so on. You can just store a single item in each array element, so in your example you cannot have a "title" element and an "author" element in each array position.

You could do something like this, however:

var books = new Array();
books[0] = "Moby Dick";
books[1] = "Jane Eyre";

var booksauthors = new Array();
booksauthors[0] = "Melville";
booksauthors[1] = "Bronte";

document.write(books[0] + " is by " + booksauthors[0]);
document.write(books[1] + " is by " + booksauthors[1]);

I see you have a "rating" property as well. JavaScript doesn't support "real" multi-dimensional arrays, but you can simulate them: Check out this link.
 

Rage187

Lifer
Dec 30, 2000
14,276
4
81
thanks for the help. I've been screwing around with Appjet and ran into this brick wall.