paulmo 3 Posted December 19, 2014 Report Share Posted December 19, 2014 Hi W3, this array-within-array should print out Students 1, 2, 3 and their averaged grades, but it's only printing out Student 3 & average, and no console errors. It works fine substituting console.log, so the problem is my innerHTML part. Thanks in advance for direction. document.addEventListener("DOMContentLoaded", function(){var grades = [[89, 77, 78], [76, 82, 81], [91, 94, 89]];var total = 0;var average = 0.0;for (var row = 0; row < grades.length; row++){ for (var col = 0; col < grades[row].length; col++){ total += grades[row][col];} average = total / grades[row].length; divid = document.getElementById("nice"); divid.innerHTML = 'Student ' + parseInt(row+1) + 'average: ' + average.toFixed(2); total = 0; average = 0.0;}}); Quote Link to post Share on other sites
justsomeguy 1,135 Posted December 19, 2014 Report Share Posted December 19, 2014 You're overwriting innerHTML each time, not adding to it. Quote Link to post Share on other sites
paulmo 3 Posted December 20, 2014 Author Report Share Posted December 20, 2014 Thanks JSG, your teach a man to fish approach is the best. divid.innerHTML += 'Student ' + parseInt(row+1) + ' average: ' + average.toFixed(2) + '<br>'; Quote Link to post Share on other sites
davej 251 Posted December 20, 2014 Report Share Posted December 20, 2014 It's actually best to try not to modify the DOM inside a loop. <!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>title</title><style>td,th,table{border:1px solid #999;text-align:center;}</style><script>document.addEventListener("DOMContentLoaded", function(){var grades = [[89, 77, 78], [76, 82, 81], [91, 94, 89]];var total = 0;var average = 0.0;var str = '<table><tr><th>Student</th><th>Average</th></tr>';for (var row = 0; row < grades.length; row++){ for (var col = 0; col < grades[row].length; col++){ total += grades[row][col];} average = total / grades[row].length; str += '<tr><td>'+ parseInt(row+1) + '</td><td>' + average.toFixed(2) + '</td></tr>'; total = 0; average = 0.0;}str += '</table>';document.getElementById("nice").innerHTML = str;});</script></head><body><div id="nice"></div></body></html> Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.