Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to create a multidimensional array to hold a generated grid. The problem is I'm used to doing this in java, but doing it in javascript is deceptively harder. I know there are arrays of arrays rather than the standard java style and this is what is causing the confusion.

So in Java I'd expect to do this:

private static int[][] anyGrid(int rows, int cols) {
    int[][] grid = new int[rows][cols];
    return grid;
}

Say rows and cols were variables of 3. What would happen, is that would create something like this:

grid is:

[0,0][0,1][0,2]
[1,0][1,1][1,2]
[2,0][2,1][2,2]

But the actual entries would be empty. So if I wanted to access the first entry I'd do: grid[0][0], except this would be empty, unless I went grid[0][0] = 1; for example.

However doing this in javascript I'm at a loss.

var grid = new Array(new Array(cols));

Simply produces an array: grid[0][0]-grid[0][5]. So one array with an internal array of length 6.

Which is.. not quite what I'm after.

How would I make it so that it is empty, but multidimensional beyond the first row?

Thank you

share|improve this question

1 Answer 1

up vote 1 down vote accepted

You can try this:

var grid = [], cols = 3, rows = 4
for (i = 0; i < cols; i++)
    grid.push(new Array(rows))

Or swap the cols with rows.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.