2

This is probably a fairly simple way to do it, but I ask since I did not find it on google.

What I want is to add an array under another.

var array = [];

array[0]["username"] = "Eric";
array[0]["album"] = "1";

Something like this, I get no errors in Firebug, it does not work. So my question is, how does one do this in javascript?

4
  • you should NOT use array as variable name since it can be confused with the Array object. Commented Dec 11, 2009 at 9:31
  • Javascript IS case sensitive. Commented Dec 11, 2009 at 9:36
  • it is, but well, it wasn't an answer, rather an advice. Commented Dec 11, 2009 at 9:40
  • I only use "array" as a variable name, in this example here =) Commented Dec 11, 2009 at 9:40

4 Answers 4

7
var a= [
 { username: 'eric', album: '1'},
 { username: 'bill', album: '3'}
];
Sign up to request clarification or add additional context in comments.

4 Comments

thx a lot! men vist du da ønsker å legge til flere i arrayet i ettertid da? I mitt tilfellet er det en loop
I'm so sorry, was so happy for your reply, I wrote it in my language. What I would say is: thx a lot! but shown when you want to add more in the array later then? In my case it is a loop
var a = []; a.push({username: "foo", album: "3"})
This is an array that contains objects. He wants an array that contains arrays.
1

try something like this

array[0] = new Array(2);
array[1] = new Array(5);

More about 2D array here

Comments

0

You should get an error in Firebug saying that array[0] is undefined (at least, I do).

Using string as keys is only possible with hash tables (a.k.a. objects) in Javascript.

Try this:

var array = [];
array[0] = {};
array[0]["username"] = "Eric";
array[0]["album"] = "1";

or

var array = [];
array[0] = {};
array[0].username = "Eric";
array[0].album = "1";

or simpler

var array = [];
array[0] = { username: "Eric", album: "1" };

or event simpler

var array = [{ username: "Eric", album: "1" }];

Comments

0

Decompose.

var foo = new Array();
foo[0] = {};
foo[0]['username'] = 'Eric';
foo[0]['album'] = '1';

Comments

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.