Reputation: 4267
I'm running a js code and in some part of it there is a definition of an array which I don't get what it means , it looks like this :
var myArray = new Array();
myArray[myNum] = new Array();
myArray[myNum].push(value1);
I don't get why there is an index of the array at the second line , is it a two dimensional array ? I'll appreciate if you can help me with this.
thanks
Upvotes: 0
Views: 73
Reputation: 2186
Let me try to explain your code....
Explanation:
var myArray = new Array(); // (1)
myArray[myNum] = new Array(); // (2)
myArray[myNum].push(value1); // (3)
(1) This creates a new empty array . It could be 1D, 2D, 3D. Currently it has nothing. At this point you array should look like this..
myArray= [];
(2) This creates another empty Array in "myArray" at index "myNum". Let us assume myNum=5;
So
myArray[5] = new Array();
Will give
myArray =[[]];
(3) This will push value1 into myArray at index "myNum". Let us again assume myNum=5 and value1 = 1,2,3;
So
myArray[5].push(1,2,3);
Will give
myArray=[[1,2,3]]
Upvotes: 1
Reputation: 29166
var myArray = new Array();
Creates an array.
myArray[myNum] = new Array();
Creates an array in myArray
's myNum
index.
myArray[myNum].push(value1);
Stores valuea1
into the array (adds the element at the last, in this case at 0
-th index) stored in myArray[myNum]
.
Yes, your assumption is right - after the execution of the three statements a two dimensional array is created, which looks something like this -
[....., [value1], ......] // the inner array is stored at "myNum" index
To access value1
, you can now do -
myArray[myNum][0];
See the doc for push.
Upvotes: 5
Reputation: 12390
This code just creates an array with an array at index myNum
. Lets break the code down.
var myArray = new Array();
//Create a new array
myArray[myNum] = new Array();
//At index 'myNum' which is a variable presumably holding an index - create a new array
myArray[myNum].push(value1);
//push variable `value1` to the new array at index myNum of myArray.
Upvotes: 1