paulmo Posted December 19, 2014 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;}}); Link to comment Share on other sites More sharing options...
justsomeguy Posted December 19, 2014 Share Posted December 19, 2014 You're overwriting innerHTML each time, not adding to it. Link to comment Share on other sites More sharing options...
paulmo Posted December 20, 2014 Author 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>'; Link to comment Share on other sites More sharing options...
davej Posted December 20, 2014 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> Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now