Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Object-Oriented JavaScript: Challenge Building Constructor Methods and Generating Objects createSpaces() Method Solution

Another way to for-loop through spaces

What about this?

createSpaces() { const spaces = []; for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { let space = new Space(i, j); spaces.push(space); } } return spaces; } I think it is short and concise. Anyway, tell me if I wrong.

3 Answers

Steven Parker
Steven Parker
216,149 Points

This creates a different kind of structure from the one in the video. The video routine creates a 2-D arrangement that is "columns" wide and "rows" deep.

But this creates a simple (1-D) array that is "rows' × "columns" long. You could refactor the code to work this way, but you'd need to change all the references from 2-D (like "spaces[row][column]") to 1-D (like "spaces[row * column]").

Siddharth Pande
Siddharth Pande
9,046 Points

In the code posted above by Miguel Barra if we change { let space = new Space(i, j)..... to {const space = new Space(i, j)........ what difference will we see? ..... please explain.

I also wrote the same nested loop to create the 1D array. Personally, I was mixing definitions of 'nested level' and 'dimension'. As my array consists of an array with arrays of depth 1, giving a total depth of 2, I thought I'd met the brief.

Having watched the video and also heard the explanation that we are essentially chunking the 1D version into columns so we can more easily access them later. I was a lot happier.

// 2D version
[ [ [0,0],[0,1],...,[0,5] ] , [ [1,0],[1,1],...,[1,5] ] ,..., [ [6,0],[6,1],...,[6,5]] ]

// 1D version
[[0,0],[0,1],...,[0,5],[1,0],...,[5,5],[6,0],...,[6,5]]

I wish I could colour the brackets!

Siddharth Pande
Siddharth Pande
9,046 Points

I understood the difference between the two approaches by actually drawing out the arrays using both methods using a pencil and paper. You may try this way to understand it better. I could have posted the drawing had there been a way to do so in here.

Steven Parker
Steven Parker
216,149 Points

Markdown formatting allows you to include images, as long as they are hosted somewhere you can reference with a URL. And there are plenty of image hosting services available, and some of them are free.