I do not understand the table statement

advertisements

I am following the 2D breakout game tutorial on the Mozilla website. There is a bit of code that I do not understand.

var brickRowCount = 3;
var brickColumnCount = 5;
var brickWidth = 75;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;

var bricks = [];
for(c = 0; c < brickColumnCount; c++) {
    bricks[c] = []; // <-- here
    for(r = 0; r < brickRowCount; r++) {
        bricks[c][r] = { x: 0, y: 0 }; // <-- here
    }
}

I understand in general what the code does, however, there are a few lines that are unclear exactly what they do. According to the website, "We will hold all our bricks in a two-dimensional array. It will contain the brick columns (c), which in turn will contain the brick rows (r), which in turn will each contain an object containing the x and y position to paint each brick on the screen."

I have put comments next to the lines of code that I specifically do not understand. Can someone please clarify exactly what these statements mean?

Thank you


it is creating a multidimensional array, or another way to call it, an array of array.

Each element of the array is another array, so to access them you need to use multiple [] for each dimension.. And just like any other array, they need to be initialized.

So here

bricks[c] = [];

it is initializing for each element of array bricks an array

bricks[c][r] = { x: 0, y: 0 };

here is storing an object in the position r in the array bricks[c] (which means the element in the position c in array bricks is an array too)