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
mckbas
14,166 PointsLoop doesn't iterate through my array properly?
Each time I add an object to my array, the array iterates through each item. I'd just like it to display the latest addition. Here is a link to the project: http://mabasinger.infprojects.fhsu.edu/studentscores/
var $ = function (id) { return document.getElementById(id); };
var scoreValues = []
var studentsScores = []
var html = "";
var displayScores = function () {
for (var i = 0; i < studentsScores.length; i++) {
html = html.concat(studentsScores[i]["firstName"], " ", studentsScores[i]["lastName"], ": ", studentsScores[i]["score"])
}
$("scores").innerHTML = html
};
var addScore = function () {
var score = parseInt($("score").value);
scoreValues.push(score)
var counter = 0;
var totalScoresValue = 0;
while(counter !== scoreValues.length) {
totalScoresValue += scoreValues[counter];
counter += 1;
}
var average = totalScoresValue / counter;
$('average_score').value = average;
var newStudent = {
firstName : $("first_name").value,
lastName : $("last_name").value,
score : $("score").value
};
studentsScores.push(newStudent)
// get the add form ready for next entry
$("first_name").value = "";
$("last_name").value = "";
$("score").value = "";
$("first_name").focus();
displayScores();
};
var clearScores = function () {
// remove the score data from the web page
$("average_score").value = "";
$("scores").value = "";
$("first_name").focus();
};
var sortScores = function () {
};
window.onload = function () {
$("add_button").onclick = addScore;
$("clear_button").onclick = clearScores;
$("sort_button").onclick = sortScores;
$("first_name").focus();
};
2 Answers
Josh Bruce
15,429 PointsYour displayScores function is concatenating the 'html' variable to it's self every time it is called. You need to either empty the variable before iterating through the for loop or declare the variable within the function's scope instead of globally.
Garrett Shaler
5,785 PointsI think the problem is the array length of the student scores during the first iteration of the loop it reads (i = 0;check if 0 < 0; add one to 0 at the end of the loop) so it never executes. You should think of the solution yourself this is homework if I am not mistaken.
Michael Liendo
15,326 PointsMichael Liendo
15,326 PointsWas about to submit an answer then I saw the .edu address. Is this for homework?