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

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Student Record Search Challenge Solution

Yixi Guan
Yixi Guan
7,927 Points

Why does the second search result appears after the first result.

Hi This is the final challenge in JavaScript loops arrays and objects.

It looks like my code is exactly like the teacher's code except the print method(I still use ducument.write). But unlike teacher's program, that the second search result will overwrite the first result, in my program, the second result will just appear after the first result. The third one too.

I don't know what I did wrong. Below is my code:

var search; var student; var message = '';

function print(message) { document.write(message); }

function getStudentReport( student ){ var report = '<h3>Student: ' + student.name + '</h3>' ; report += '<p>Track: ' + student.track + '</p>' ; report += '<p>Achievements: ' + student.achievements + '</p>' ; report += '<p>Points: ' + student.points + '</p>'; return report; }

while (true) { search = prompt('input a student name'); if (search === null || search.toLowerCase() === 'quit'){ break; } for (var i = 0; i < students.length; i += 1) { student = students[i]; if ( search === student.name ) { message = getStudentReport( student ); print(message); } } }

1 Answer

Yixi Guan
Yixi Guan
7,927 Points

I changed the print(message) function, and it works fine now. I still don't know why document.write won't work the same, but for now problems solved.