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 trialGary Calhoun
10,317 PointsMine works but wonder if it can be improved?
I got it working finally but I was wondering if any dry programming could be added to this or anything changed to my existing solution all together?
var students = [
{name: 'Gary', track: 'Javascript', achievements: 10002, points: 5133 },
{name: 'Mark', track: 'Ruby', achievements: 345, points: 1003 },
{name: 'Peter', track: 'CSS', achievements: 200, points: 600 },
{name: 'Mary', track: 'Design', achievements: 402, points: 706 },
{name: 'Jane', track: 'PHP', achievements: 678, points: 1240 }
];
function print(message) {
document.write(message);
}
for (var i= 0; i < students.length; i += 1 ){
//variables display the answers
print(name = '<h2> Name: ' + students[i].name + '</h2>');
print(track = '<p>Track: ' + students[i].track + '</p>');
print(achieve = '<p>Achievements: ' + students[i].achievements + '</p>');
print(points = '<p>Points: ' + students[i].points + '</p>');
}
2 Answers
Colin Bell
29,679 PointsYou could set it up so that the print function only gets called once per student:
for (var i= 0; i < students.length; i += 1 ){
print('<h2> Name: ' + students[i].name + '</h2>' +
'<p>Track: ' + students[i].track + '</p>' +
'<p>Achievements: ' + students[i].achievements + '</p>'+
'<p>Points: ' + students[i].points + '</p>');
}
Shane Meikle
13,188 PointsA little late to the party, but what if something was added to the object? Your code is restricted to only the explicit values you stated. I used the following:
for (var i = 0; i < students.length; i++)
{
document.write('<h4>' + students[i].name + '</h4>');
for (var prop in students[i])
{
document.write(prop + ": " + students[i][prop] + "<br/>");
}
}
and it seems to handle the initial requirements plus keeps it open for additions/subtractions to the objects.
Gary Calhoun
10,317 PointsYes thank you this looks a lot more flexible:)
Rick Gates
11,061 PointsIn your example, wouldn't the name property print to the page twice? Once using the h4 element then again when it loops through the nested loop? Removing the line that writes the name in an h4 element would fix this.
Gary Calhoun
10,317 PointsGary Calhoun
10,317 Pointsthanks, haha I knew it had to be something simple when I saw myself write print a million times I knew something wasn't right.