Just use an object:
var books = {book1: ['book1 title', 'book1 - title2']};
books['book2'] = ['book2 titles'];
books.book3 = [];//works, too
books.book3.push('foobar');
If you insist on having variables that reference a particular array, that's very easily done:
var book2 = books.book2;//arrays are objects, so:
book2.push('A second title');
console.log(books.book2[1]);//logs "A second title"
Easy-peasy. on the dynamic names front, just a quick example:
books['book' + someVar] = [];
Works just fine.
As @raghaw pointed out, perhaps you could do with some explaining:
JavaScript doesn't really support associative arrays as such, instead objects are used (even Array's are just "pimped" objects, but that's a different matter)
You can create a new instance of any object by calling the construct (new X()
, like you did), but in case of native object types (like Array and Object), that's not to be recommended (new Array(10);
and new Array('10')
behave differently, for example).
In those cases the literal notation is to be preferred:
var wrong = new Object();//not "wrong", but impredictable
var better = {};//or new [whateverTypeOfObject]();
//ditto for arrays:
var dangerous = new Array();
var safe = [];
To assign an object/array with a certain set of values already there, simply fill them in:
var myObject = {key: "value",
theValue: {can: 'be',
anything: ["even", "another", "object"]}
};
The data can be accessed both by using the dot-notation or the bracket notation:
console.log(myObject.theValue['can']);//be
//===
console.log(myObject.theValue.can);//be
//===
console.log(myObject["theValue"]["can"]);//be
If you're using variables as keys, you'll have to use the bracket notation. If you feel like you need more info check out MDN, spend some time on that site - it's a good reference on JS