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 trialGerman Iakovlev
5,506 PointsUsing students.indexOf(search) for the challenge
I have been trying to use the array.indexOf method to go to the specific student from the students array. But somehow the studentID has always a value of -1. And it causes the following error Uncaught TypeError: Cannot read property 'name' of undefined(…) on this line:
studentList += '<h2>Student: ' + students[studentID].name + '</h2>';
function print(HTML) {
document.getElementById('output').innerHTML = HTML;
};
var studentList = '';
while (true) {
var search= prompt('give student name you want to look up');
//Use the student name for getting the index of the student in the array
var studentID = students.indexOf(search);
console.log(studentID);
studentList += '<h2>Student: ' + students[studentID].name + '</h2>';
studentList += 'Track' + ': ' + students[studentID].track + '<br>';
studentList += 'Achievements: ' + students[studentID].achievement + '<br>';
studentList += 'Points: ' + students[studentID].achievement + '<br><br>';
print(studentList);
};
Would be awesome if someone could tell me where it went wrong :) Thanks a lot!
1 Answer
Ryan Zimmerman
3,854 PointsSo you have an array of objects. The indexOf will only work on the array. So if it was just an array of numbers that would work. Use a "forEach" and pass it a "for in loop" that will look at each object.
German Iakovlev
5,506 PointsGerman Iakovlev
5,506 PointsThank you for the heads up, Ryan!
Will look into that.