用js写一个学生成绩考评
时间: 2024-09-11 18:13:44 浏览: 62
在JavaScript中,我们可以创建一个简单的学生成绩考评类(StudentGradeEvaluator),这个类可以包含学生的姓名、课程列表以及计算总分和平均分的方法。以下是一个基础的例子:
```javascript
class StudentGradeEvaluator {
constructor(name) {
this.name = name;
this.grades = {}; // 使用对象存储每个课程的成绩
}
addCourse(course, grade) {
if (grade >= 0 && grade <= 100) { // 确保成绩在合理范围内
this.grades[course] = grade;
} else {
console.log(`Invalid grade for ${course}. Grade should be between 0 and 100.`);
}
}
calculateTotalScore() {
let total = 0;
Object.values(this.grades).forEach(grade => total += grade);
return total;
}
calculateAverageScore() {
const total = this.calculateTotalScore();
if (Object.keys(this.grades).length > 0) {
return total / Object.keys(this.grades).length;
} else {
return 0; // 如果没有成绩,返回0
}
}
printReport() {
console.log(`Name: ${this.name}`);
console.log("Courses and Grades:");
for (const [course, grade] of Object.entries(this.grades)) {
console.log(`${course}: ${grade}`);
}
console.log(`Total Score: ${this.calculateTotalScore()}`);
console.log(`Average Score: ${this.calculateAverageScore()}`);
}
}
// 使用示例
const student = new StudentGradeEvaluator("张三");
student.addCourse("数学", 95);
student.addCourse("英语", 85);
student.printReport();
```
阅读全文