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

2
  • 1
    Side note: Use [] instead of new Array();. Commented Jan 4, 2013 at 15:06
  • To support jbabey's statement: stackoverflow.com/questions/2280285/… Commented Jan 4, 2013 at 15:15

5 Answers 5

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.
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for the answer, it won't let me select you now but I will later if I remember, this is how I tried it earlier but I must've done something wrong.
Maybe you made a typo or something, then ;-) Always glad to be of help!
how would I get the length of derps[0]?
@user1420493: derps[0].length
Okay, I forgot to update some code so that wasn't working when I was trying it, that's why I asked :P thanks anyways
|
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);

1 Comment

Good answer, you covered it all.
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] = [];

Comments

0

Easy:

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

Comments

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.

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.