0

Let's say I have an array named derps and then I make an array inside it:

derps[0]=new Array();

how do I get/set data in the newly created array derps[0]?

Jeff Noel
  • 7,500
  • 4
  • 40
  • 66
Zachrip
  • 3,242
  • 1
  • 17
  • 32

5 Answers5

2

Simply do this:

derps[0][0] = 'foo';
derps[0][1] = 'bar';
derps[0].push('foobar');
derps[0] = derps[0].concat([5,6,7]);
// Etc, etc.

console.log(derps[0][1]); // 'bar'
console.log(derps[0][2]); // 'foobar'
console.log(derps[0]);    // ["foo", "bar", "foobar", "foobar", 5, 6, 7]

Basically, access derps[0] like you'd access any other array, because it is an array.
I'm not going to list All methods you can use on derps[0] ;-)

Also, instead of:

derps[0] = new Array();

You can use the "array literal" notation:

derps[0] = []; // Empty array, or:
derps[0] = ['foo', 'bar', 'foobar']; // <-- With data.
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
2

You can create the array with data already in it:

derps[0] = [1, 2, 3];

You can assign values to the array:

derps[0] = new Array();
derps[0][0] = 1;
derps[0][1] = 2;
derps[0][2] = 3;

You can push values to the array:

derps[0] = new Array();
derps[0].push(1);
derps[0].push(2);
derps[0].push(3);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

You can push data into the new array:

derps[0].push("some data");

As an aside: you may also use an array literal to create derps[0]:

derps[0] = [];
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
0

If you really wish to instantiate the type of the variable before, you can proceed this way (JSFiddle).

var derps = [];
derps[0] = [];

derps[0][0] = "test";
derps[0][1] = "test2";

document.write(derps[0][1]);​

Don't forget to write var if you don't want the variable to be global.

Jeff Noel
  • 7,500
  • 4
  • 40
  • 66
0

Easy:

var derps = [];
derps.push([]);
derps[0].push('foo');
derps[0].push('bar');
asgoth
  • 35,552
  • 12
  • 89
  • 98