Lev Lev - 4 months ago 4
Javascript Question

Trying to get number out of array getting NaN error

Getting an NAN error when trying to get the total of grades in the class.
Tried parseInt() and .vale on students[i].grade please help I am totally new here. Thank you.

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);
}


Output from console log is:

80
NaN
77
NaN
88
NaN
95
NaN
68
NaN

Answer

1) You need to initialize average: var average = 0;

2) You also don't need .value since value is not a valid property.

average += Number(students[i].grade);

3) You don't need to redundantly cast a number value into a number with Number() if you can be sure all accessed properties are already number types.

This will do just fine:

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);

Comments