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
Oscar Mauricio Lancheros Murillo
3,608 PointsFinal Test Arrays, Objects, loops question
Hello, I was wondering why in this code my object keeps printing right below the last object was printed. I would need it to show only the last that I did print.
var message = '';
var student;
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
var input = 0;
while (input !== 'quit') {
input = prompt('Busca estudiante\n Para salir escribe "quit"')
for (i= 0; i<students.length; i++){
if (input === students[i].name){
student = students[i];
message += '<h2>Student: ' + student.name + '</h2>';
message += '<p>Track: ' + student.track + '</p>';
message += '<p>Points: ' + student.points + '</p>';
message += '<p>Achievements: ' + student.achievements + '</p>';
print(message);
}
}
}
3 Answers
Sean T. Unwin
28,690 PointsIf I understand the question correctly, you will want to move the print(message); statement outside of the for loop.
Sean T. Unwin
28,690 PointsYou will want to reset the message variable to be empty at the beginning of the if statement with, message = '';. This line would make the most sense after the student = students[i]; line and before the building of the message. The point being is that you want to empty an old message before creating a new one.
Oscar Mauricio Lancheros Murillo
3,608 PointsSean T. Unwin
28,690 PointsI provided a new answer at about the same time you posted this. :)
Oscar Mauricio Lancheros Murillo
3,608 PointsOscar Mauricio Lancheros Murillo
3,608 PointsNo, I need it to print just once, and when I need to print another one the last one would not be there, only the new one.
Sean T. Unwin
28,690 PointsSean T. Unwin
28,690 PointsYeah, I got thinking about it a little more after I commented hastily. ;-)