-1

I have a two dimensional array which I created like this

var books = new Array();  // create an Array
        var book1 = new Array();
      book1.push("1");
      book1.push("adfgsdg");
      book1.push("dfgsdfg");
      book1.push("dfgds");
      book1.push("44.95");
      book1.push("dfgsd");
      book1.push("dfgsdg");
      books.push(book1);
    var book2 = new Array();
      book2.push("2");
      book2.push("gdhff");
      book2.push("fghfd");
      book2.push("fghdf");
      book2.push("44.95");
      book2.push("2000-12-16");
      book2.push("fghfghd");
      books.push(book2);

can you tell me how to dynamically create a new book3, book4.... array and push into the books array.

1
  • 3
    Why can't you just continue to create book3 and book4 like book2?
    – closure
    Commented Dec 15, 2012 at 10:30

2 Answers 2

2

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

4
  • Is it not too confusing for a beginner?
    – closure
    Commented Dec 15, 2012 at 10:31
  • 1
    You may want to explain your construct
    – closure
    Commented Dec 15, 2012 at 10:31
  • You can just tell that in Javascript every object is actually an associative array. I think it is reasonably easy to understand.
    – mastazi
    Commented Dec 15, 2012 at 10:34
  • I think, the syntax of a newly learned language is the first thing one should undertand. So if this really needs more than a few words of explanation one should revist a good book.
    – Yoshi
    Commented Dec 15, 2012 at 10:36
0

First of all I think that the answer by Elias is very good. However, if you are not in the mood of going OO, just create books 3 and 4 as raghavv told in the comment, then push them all in the books array

books.push(books1);
books.push(books2);
books.push(books3);
books.push(books4);

The result of it will be actually something like

var books[
    books1[value1, value2, value3],
    books2[value1, value2, value3],
    books3[value1, value2, value3],
    books4[value1, value2, value3]
];
8
  • 1
    You're wrong there mate, the result won't contain books1 as such, just a reference to that array. BTW: Array's are objects, that inherit from the Object.prototype, too. They're augmented instances, nothing more. so if you write var x = []; x['foo'] = 'bar'; you're working on an object. There's nothing OO about using object literals... you're using them too, actually Commented Dec 15, 2012 at 10:47
  • You are right it is a reference, but if I'm not wrong you still can get values as books[x][y] which is what really matters to us. Yes of course you can't avoid using objects in javascript, I think this is what makes this language special.
    – mastazi
    Commented Dec 15, 2012 at 10:57
  • That's not entirely what I meant to say. I'm being pedantic, sure, but it could help ppl avoiding quite common mistakes if only they knew that Arrays don't exist in JS, if you apply a for...in loop to them, and check the type of the index, you'll notice it's a string: arrays are object literals, with a few extra methods, nothing more. Also: of course you can't not use objects: even functions are objects (JS is considered a functional language, that's what really makes it special) Commented Dec 15, 2012 at 11:02
  • 1
    Well, not the constructor is what makes this such an incredibly powerful concept, but the fact that functions can be passed to other functions as arguments, they can be the return value of a function, they can be either an entire statement or an expression closures etc... all very powerful things. Commented Dec 15, 2012 at 11:18
  • 1
    methods are just functions, and all functions are, by definition, objects. A method is just a function, invoked in the context of an object: Array.prototype.slice.apply(arguments,[0]); calls the function object, that is referenced by Array.prototype.slice in the context of an arguments instance. As far as JS is concerned: performance is hard to predict different engines often differ (dramatically), but on the whole, I think I'm right in saying that recursion is the best way to go (like it is in any other functional language) Commented Dec 15, 2012 at 18:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.