shivam.k shivam.k - 1 month ago 4
Javascript Question

Unable to understand what Javascript new Array( new Array(5,4,3,2,1,0),new Array())

Please tell me what this code is doing ,is it creating multi dimension array(which i think it is not) ?

code snippet..

var hanoi_peg = new Array(
new Array( 5, 4, 3, 2, 1, 0 ),
new Array( -1, -1, -1, -1, -1, -1 ),
new Array( -1, -1, -1, -1, -1, -1 )
);


thanks..

Answer

Log it into your console and you will see that it creates an array of arrays and it serves for the same purpose.

var hanoi_peg = new Array(
   new Array(  5,  4,  3,  2,  1,  0 ),
   new Array( -1, -1, -1, -1, -1, -1 ),
   new Array( -1, -1, -1, -1, -1, -1 )
 );

console.log(hanoi_peg);

To access each item you must use double [] operators like this. For accessing the first item of the first array you need to call

console.log(hanoi_peg[0][0]);

It is same as

var firstArray = hanoi_peg[0];
var firstItemOfFirstArray = firstArray[0]; // hanoi_peg[0][0]