Array under another array in javascript
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 un开发者_JAVA百科der 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?
var a= [
{ username: 'eric', album: '1'},
{ username: 'bill', album: '3'}
];
try something like this
array[0] = new Array(2);
array[1] = new Array(5);
More about 2D array here
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" }];
Decompose.
var foo = new Array();
foo[0] = {};
foo[0]['username'] = 'Eric';
foo[0]['album'] = '1';
精彩评论