I need to be able to add a student and a grade. however, I am having a difficult time figuring out how to enter a grade. This is what I have so far. When I run the program like this I get: [ Student { name: 'Bob', grades: [], totalGrades: 0 } ]
Any help would be appreciated!
The commented out section was an attempt at adding grades, however, I did not work at all.
function Student(name){
this.name = name;
this.grades = [];
this.totalGrades = function(){
this.totalGrades = 0;
this.grades.forEach(grade => {
this.totalGrade += grade;
})
}
}
function Students(){
this.students = [];
// this.grades = [];
/* this.addGrade = function(grade){
this.grades.push(grade);
}*/
this.addStudent = function(student){
this.students.push(student);
}
this.calcTotalGrades = function(){
this.students.forEach(student => {
student.totalGrades();
})
}
}
let students = new Students();
students.addStudent(new Student('Bob'));
students.calcTotalGrades();
console.log(students.students);
Try this function, as a method of your Students
:
this.addGrade = function(student,grade) {
this.students.forEach(student => {
if(student.name === student)
student.grades.push(grade)
}
}
To add a new grade:
students.addGrade('Bob',10);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.