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

JavaScript Object-Oriented JavaScript: Challenge Rendering the Game Rendering the Spaces, Board, and Tokens Solution

YONGJIN KIM
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
YONGJIN KIM
Full Stack JavaScript Techdegree Graduate 20,287 Points

How about the for-loop for drawHTMLBoard() Method?

In the previous instruction, it says using a for-loop for iteration of 2D array of space objects. However, in this video, the teacher shows a for-of loop as a solution, which is good to show a different way to execute the code. Meanwhile, I still want to know the solution using a for-loop. Please see if the following works.

drawHTMLBoard() { for(let i = 0; i < this.column; i++) { for(let j = 0; j < this.row; j++) { this.spaces[i][j].drawSVGSpace(); } } }

1 Answer

Steven Parker
Steven Parker
229,644 Points

Have you tested it yourself? Plug that into the code and try it out!

It looks like you've created a good "for" loop translation of the "for...of" code, with one possible exception. I'd expect the inner loop variable to be the first index. (so "spaces[j][i]" instead of "spaces[i][j]"). But test it and see.

YONGJIN KIM
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
YONGJIN KIM
Full Stack JavaScript Techdegree Graduate 20,287 Points

Hi Steven! Thank you for your answer. I did my own test and updated the order of the outer and inner index as you suggested. I think my index order is likely suitable for me because I want to iterate the array in order.

For example, you have this 2D array:

var cubes = [
 [1, 2, 3],
 [4, 5, 6],    
 [7, 8, 9],
];

Then, iterate the array with [inner][outer] index as you suggested

for(var i = 0; i < cubes.length; i++) {
    for(var j = 0; j < cubes[i].length; j++) {
        console.log("cube[" + j + "][" + i + "] = " + 
        cubes[j][i]);
    }
}

The output of the above:

cube[0][0] = 1
cube[1][0] = 4
cube[2][0] = 7
cube[0][1] = 2
cube[1][1] = 5
cube[2][1] = 8
cube[0][2] = 3
cube[1][2] = 6
cube[2][2] = 9

Technically, you can through all the value of the array. But it is not the order to iterate I like to.

Steven Parker
Steven Parker
229,644 Points

I thought that was the order the "for...of" loop was doing, but I was a bit distracted when I first looked at that.
But now you've proven your "for" version is an accurate alternate!