Thursday, 30 August 2018

Create a multidimensional array in the loop

I want to create a multidimensional array like this:

array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
array[1][21,22,23,24,25,26,27....]
array[.][....]

How can I do this in Javascript?
I have tried this:
var squares = new Array();
        for(var i = 1; i <= 8; i++)
        {
            for(var j = 1; j <= 20; j++)
            {
                squares.push(i, j);
            }

        }

How can I accomplish this?

You can do something like this:
var squares = new Array();
for(var i = 0; i <= 8; i++)
{
    squares[i] = new Array();
    for(var j = (i * 20) + 1; j <= 20 * i + 20; j++)
        if (squares[i] == null)
            squares[i] = j;
        else
            squares[i].push(j);
}

Output comes like:
array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
array[1][21,22,23,24,25,26,27....]

0 comments:

Post a Comment