在此任务中,我应该编写一个JavaScript程序来计算所列学生的平均成绩: 大卫80,维诺斯77,迪维亚88,石塔95,托马斯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}`);
答案 0 :(得分:1)
初始化为0 let 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}`);