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 trialMiguel Barra
6,855 PointsAnother 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
231,271 PointsThis 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]
").
Joseph Lander
Full Stack JavaScript Techdegree Graduate 27,765 PointsI 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]]
Joseph Lander
Full Stack JavaScript Techdegree Graduate 27,765 PointsI wish I could colour the brackets!
Siddharth Pande
9,046 PointsI 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
231,271 PointsMarkdown 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.
Siddharth Pande
9,046 PointsSiddharth Pande
9,046 PointsIn 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.