首页 > 解决方案 > 计算学生的平均成绩和成绩

问题描述

在这个任务中,我应该编写一个 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}`);

标签: javascriptarraysfor-loop

解决方案


初始化为 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}`);


推荐阅读