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
Spencer Christensen
Courses Plus Student 8,180 PointsQuestion on Randy Hoyt's Robot Maze
Hi team Treehouse!
Firstly, let me tell you that I LOVED Randy's workshop. Just going through a program from start to finish has done WONDERS in helping me understand how to think about program design. Please keep workshops coming!
I have one question that has been bugging me. It is when Randy creates spaces on his Maze object. Here is the code:
this.directions = ["north", "east", "south", "west"];
this.spaces = [];
var x, y;
//for loop goes through each column, creating an array for it
for (x=1; x<=width; x+=1) {
this.spaces[x] = []; //In each column create empty array
for (y=1; y<=height; y+=1) { //add one element to array for each space in column
this.spaces[x][y] = new MazeSpace(this.directions);
};
};
};
I have no clue how/what this.spaces[x][y] is creating the array within the arrays. Can you point me to some documentation that explains this syntax (i.e. property[array1][array2]). I would love to know not just THAT this works, but how.
He uses a similar syntax in his canMove function on the Robot object:
if (this.spaces[forwardX][forwardY][opposites[direction]]) {
return false; //checks to see if there is a wall on the forward space
};
Thanks!
1 Answer
Dave McFarland
Treehouse TeacherHi,
You use this kind of syntax -- items[0][1] -- when have nested arrays. That is, an array that is itself an element in an array:
var items = [
[1, 2],
[3, 4],
[5, 6]
];
Each element in the items array above is itself an array. So items[0] is [1,2]. If you want to access number 3 above, you need to access the second element in the items array, and the first element in that array like this: items[1][0].