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 trialVaughn Council
2,419 PointsAccessing values
Jim mentions that you can write an array within an array. Example:
var cars = ["Honda", "Toyota", "Ford", ["BMW", "Benz"] ];
In this case what index would I use to access BMW? Would it be cars[3]; ?
1 Answer
Ken Alger
Treehouse TeacherVaughn;
Welcome to Treehouse!
Let's do a quick look at accessing arrays in general as a refresher. Here is your array:
var cars = ["Honda", "Toyota", "Ford", ["BMW", "Benz"] ];
As you know, if you want to access an array item you use it's index
number. JavaScript utilizes a zero based index, so in this example Honda
resides at index 0
, Toyota
at index 1
, etc.
When you get to the nested array, ["BMW", "Benz"]
, that is accessed by cars[3]
. In order to access BMW
by itself you would use cars[3][0]
, which accesses the inner array with the [3]
and then the first item in that array with the [0]
.
Does that make sense? For more information on JavaScript arrays I would point you to the Mozilla Developer's Network on them. There are, of course, lots of additional resources, but this is a great starting place.
Happy coding,
Ken
Nejc Vukovic
Full Stack JavaScript Techdegree Graduate 51,574 PointsNejc Vukovic
Full Stack JavaScript Techdegree Graduate 51,574 Points@Ken No other way to explain it :) It is what it is:)