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 trialShung Chen
6,526 Pointsonly the last student record is printed out
var students = [
{
Name: 'Oskar',
Track: 'iOS',
Achievements: 100,
Points: 1000
},
{
Name: 'Peter',
Track: 'Android',
Achievements: 200,
Points: 2000
},
{
Name: 'Adrian',
Track: 'Python',
Achievements: 300,
Points: 3000
},
{
Name: 'Betty',
Track: 'C++',
Achievements: 400,
Points: 40000
},
{
Name: 'Elaine',
Track: 'json',
Achievements: 500,
Points: 5000
}
];
var report;
var message;
function print(){
var outPut = document.getElementById(`output`);
return outPut.innerHTML = message;
}
for ( i = 0 ; i < students.length ; i++ ) {
message = `<h2> Student Name: ${students[i].Name} </h2>`;
message += `<p>Track: ${students[i].Track}</p>`;
message += `<p>Achievements: ${students[i].Achievements} </p>`;
message += `<p>Points: ${students[i].Points} </p>`;
print(message);
}
can anyone let me know why this is the case
the only difference is I did not add the student = student[i] as demonstrated in the video
I guess it is something wrong when using the function? Was getting the expected result with document.write(message) but not the print
1 Answer
Steven Parker
231,269 PointsThe "print" function is replacing the element contents each time it is used. if you want them to accumulate instead:
outPut.innerHTML += message; // add on (+=) instead of replace (=) content
And the "print" function doesn't need to "return" anything.
Shung Chen
6,526 PointsShung Chen
6,526 PointsHi Steve, does it mean all the student records actually appeared on the index.html when I run the site, but the previous 4 were replaced by the last record?
Steven Parker
231,269 PointsSteven Parker
231,269 PointsYes, but nothing is rendered until the script completes. Even if it was, it would likely be too fast to see.
Happy coding!