处理二维数组的元素
一、按列访问:外层循环对应行, 内层循环对应列。
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; document.write("Student " + parseInt(row + 1) + " average: " + average.toFixed(2) + "<br />"); total = 0; average = 0.0; }
二、按行访问:外层循环对应列, 内层循环对应行。
var grades = [ [ 89, 77, 78 ], [ 76, 82, 81 ], [ 91, 94, 89 ] ]; var total = 0; var average = 0.0; for ( var col = 0; col < grades.length; ++col) { for ( var row = 0; row < grades[col].length; ++row) { total += grades[row][col]; } average = total / grades[col].length; document.write("Test " + parseInt(col + 1) + " average: " + average.toFixed(2) + "<br />"); total = 0; average = 0.0; }