Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Joseph Turner
Full Stack JavaScript Techdegree Graduate 16,794 PointsHow does drawHTMLBoard() access 'column' and 'space'?
The 'column' and 'space' were declared within the createSpaces() method, so how does the drawHTMLBoard() method access these? Thanks in advance!
class Board { constructor() { this.rows = 6; this.columns = 7; this.spaces = this.createSpaces(); }
/**
* Generates 2D array of spaces
* @return {array} An arary of space objects
*/
createSpaces() {
const spaces = [];
for (let x = 0; x < this.columns; x++) {
const column = [];
for (let y = 0; y < this.rows; y++) {
let space = new Space(x, y);
column.push(space);
}
spaces.push(column);
}
return spaces;
}
drawHTMLBoard() {
for (let column of this.spaces) {
for (let space of column) {
space.drawSVGSpace();
}
}
}
}
1 Answer
Zimri Leijen
11,835 PointsIn the nested for loop it creates a 2 dimensional array (an array of arrays).
createSpaces() {
const spaces = [];
for (let x = 0; x < this.columns; x++) { // for each column
const column = []; // create an empty placeholder array for the column
for (let y = 0; y < this.rows; y++) { // for each row
let space = new Space(x, y); // create a space (note we're still in the column for loop)
column.push(space); // push the space into the placeholder column array
}
spaces.push(column); // push the entire column into the array
}
return spaces; // return the complete array of all rows (the rows contain the spaces and therefore columns)
}
If you type this into your console (F12)
function test() {
let array = [];
for(let i = 0; i < 7; i++){
let column = [];
for(let j = 0; j < 6; j++){
column.push({i, j})
}
array.push(column);
}
console.log(array);
}
test()
you may get a better understanding of how the loop works.
Joseph Turner
Full Stack JavaScript Techdegree Graduate 16,794 PointsJoseph Turner
Full Stack JavaScript Techdegree Graduate 16,794 PointsHi Zimri, thanks for your response. I understand the 2D array creation in the createSpaces() method. However, I was confused with how drawHTMLBoard() accessed the "const columns = [];" and the "let space = new Space;" when they were declared within createSpaces().
But I figured it out by testing it out (per your suggestion). The "for of" loop could have used any variable. I got confused because I thought the drawHTMLBoard() was using the same variables from createSpaces()... Thanks again. Appreciate it!