-4

In my code, I need an object that's equivalent to

(0,0)   (20,0)   (40,0) ...    (580,0)
(0,20)  (20,20)  (40,20) ...   (580,20)
.
.
.
(0,580) (20,580) (40,580) .... (580,580) 

These correspond to (x,y) coordinates on a grid for a game I'm making. Does Javascript have a simply abstraction for this???? I didn't find this How can I create a two dimensional array in JavaScript? answer to be satisfactory. I want a 30x30 2d array where I can access elements like arr[0][1] = [0,20] and so forth.

Community
  • 1
  • 1
Donald Knuth
  • 129
  • 4
  • You've got a 2D-array of tuples, which in JS will be represented as an array of arrays of arrays. What exactly is not satisfactory about that answer you found? It's exactly what you want, only with tuples instead of numbers. – Bergi Jun 02 '14 at 17:20

2 Answers2

0

A 2d matrix is an array of arrays. You can create it with a nested loop.

var array2d = [];
for (var i = 0; i <= 580; i += 20) {
    var subarray = [];
    for (var j = 0; j <= 580; j += 20) {
        subarray.push([i, j]);
    }
    array2d.push(subarray);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

This is about a year too late, but you can do the following:

    var array = [];
    var xIncrease = 20;
    var yIncrease = 20;

    for (var y = 0; y < 30; y++)
    {
        array[y] = [];
        for (var x = 0; x < 30; x++)
        {
            array[y][x] = "(" + x * xIncrease + ", " + y * yIncrease + ")";
        }
    }
DUUUDE123
  • 166
  • 1
  • 10