javascript - 计算学生的平均成绩和成绩
问题描述
在这个任务中,我应该编写一个 JavaScript 程序来计算所列学生的平均分:David 80、Vinoth 77、Divya 88、Ishitha 95、Thomas 68。
预期的方法是使用给定的数据创建一个数组,然后使用 for 循环遍历它。使用 for 循环很重要,因为这就是我目前正在研究的内容,并且想了解它为什么不起作用。(我还不知道如何使用 forEach 方法)
当我运行循环并返回 NaN 时会出现问题。我不知道为什么会发生,或者我在这里做错了什么。
const nameGrade = [["David", 80], ["Vinoth", 77], ["Divya", 88], ["Ishitha", 95], ["Thomas", 68]];
let sumGrades;
console.log(`Value of sumGrades right after definition: ${sumGrades}`); //this returns undefined which is expected
for (let i = 0; i < nameGrade.length; i++){
sumGrades += nameGrade[i][1];
console.log(`Value of sumGrades after the for loop: ${sumGrades}`); //this returns NaN, and I dont know why!!
}
let avg = (sumGrades/nameGrade.length);
console.log(`Value of sumGrades/array.length: ${avg}`);
解决方案
初始化为 0let sumGrades=0;
const nameGrade = [["David", 80], ["Vinoth", 77], ["Divya", 88], ["Ishitha", 95], ["Thomas", 68]];
let sumGrades=0;
console.log(`Value of sumGrades right after definition: ${sumGrades}`); //this returns undefined which is expected
for (let i = 0; i < nameGrade.length; i++){
sumGrades += nameGrade[i][1];
console.log(`Value of sumGrades after the for loop: ${sumGrades}`); //this returns NaN, and I dont know why!!
}
let avg = (sumGrades/nameGrade.length);
console.log(`Value of sumGrades/array.length: ${avg}`);
推荐阅读
- java - Java RMI 远程对象可以在次要收集中进行垃圾收集吗?
- css - IIS 10 托管网站未正确使用 CSS 文件
- app-inventor - 应用发明者 2 MockingApp
- javascript - Firebase:使用 JavaScript SDK 加入 Firestore 文档结果
- mysql - 无法通过角度从nodejs获取数据
- python - Matplotlib - 堆叠条形图和工具提示
- c# - 将 XML 序列化为文件
- android - 如何在选项卡布局中显示列表视图?
- python - 使用 2D 高斯蒙版蒙版灰度图像失败
- rust - 如何配置在连接器上具有多态性的超 0.11.x 客户端变量?