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 trialAkeia Escobar
1,957 PointsI got stuck trying to access the value
When I run this code it prints "undefined" at the top. Then name, track, etc., but the values of the object also print undefined. What am I doing wrong?
var HTML;
let students = [
{
name: 'Cayden',
track: 'C#',
achievements: 10,
points: '2123'
},
{
name: 'Akeia',
track: 'Full Stack Development',
achievements: 15,
points: '4253'
},
{
name: 'Yaya',
track: 'Front End Development',
achievements: 13,
points: '2435'
},
{
name: 'Jason',
track: 'Beginner Python',
achievements: 12,
points: '2321'
},
{
name: 'Ashley',
track: 'iOS',
achievements: '9',
points: '1324'
},
];
// print function
function print(message) {
let outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
//for loop to access array
for (i = 0; i < 4; i += 1 ) {
for (studentData in students[i]) {
HTML += '<p>' + studentData + ': ' + studentData[students] + '</br>'
}
}
print(HTML);
2 Answers
KRIS NIKOLAISEN
54,971 Points1) Initialize HTML with an empty string. Without a value you have the first undefined.
var HTML = "";
2) Access properties for the current array object students[i]
HTML += '<p>' + studentData + ': ' + students[i][studentData] + '</br>'
3) Use students.length (which equals 5 not 4) here:
for (i = 0; i < students.length; i += 1 ) {
KRIS NIKOLAISEN
54,971 PointsFrom MDN on bracket notation:
Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it.
It then goes on to give an example of accessing properties of a car object but the syntax is basically:
object['property']
For the code students[i]
is the object and studentData
is the property
The first example here is similar
Loop through the properties of an object:
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x] + " ";
}
Akeia Escobar
1,957 PointsThanks. That helps a lot!
Akeia Escobar
1,957 PointsAkeia Escobar
1,957 PointsThanks! That worked. Can you explain why
students[i][studentData]
works?It's not really clicking