在尝试获得班级中的成绩总数时出现NAN错误。 在学生[i] .grade上尝试了parseInt()和.value。我是全新的。
var students= [{name:"David", grade:80},
{name:"Vinoth", grade:77},
{name:"Divya", grade:88},
{name:"Ishitha", grade:95},
{name:"Thomas", grade:68}];
var average;
for(i = 0; i < students.length; i++){
console.log(students[i].grade);
average += Number(students[i].grade.value);
console.log(average);
}
控制台日志的输出是:
80 为NaN 77 为NaN 88 为NaN 95 为NaN 68 为NaN
答案 0 :(得分:3)
1)您需要初始化平均值:var average = 0
;
2)您也不需要.value
,因为价值不是有效的财产。
average += Number(students[i].grade);
3)如果您确定所有访问过的属性都已经是数字类型,则不需要将数字值冗余地转换为Number()
的数字。
这样做会很好:
var students= [{name:"David", grade:80},
{name:"Vinoth", grade:77},
{name:"Divya", grade:88},
{name:"Ishitha", grade:95},
{name:"Thomas", grade:68}];
var average = 0;
for(i = 0; i < students.length; i++){
console.log(students[i].grade);
average += Number(students[i].grade);
console.log(average);
}
console.log("average: ", average/students.length);
&#13;