Zachrip
Zachrip

Reputation: 3382

how to get data from an array within an array javascript

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]?

Upvotes: 0

Views: 123

Answers (5)

Jeff Noel
Jeff Noel

Reputation: 7617

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.

Upvotes: 0

Cerbrus
Cerbrus

Reputation: 72967

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.

Upvotes: 2

asgoth
asgoth

Reputation: 35829

Easy:

var derps = [];
derps.push([]);
derps[0].push('foo');
derps[0].push('bar');

Upvotes: 0

Guffa
Guffa

Reputation: 700910

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);

Upvotes: 2

bfavaretto
bfavaretto

Reputation: 71939

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] = [];

Upvotes: 0

Related Questions