处理二维数组的元素
一、按列访问:外层循环对应行, 内层循环对应列。
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; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步