具有计算平均成绩的方法的对象(姓名、索引号、table 和成绩)

Object (name, surname, index number, table with grades) with a method that calculates the grade average

所以我一直在努力解决这个大学任务。我对如何解决这个问题有一个大概的了解,但我只是想出了一些解决方案,要么不起作用,要么不真正符合任务要求。

任务看起来像这样。

使用对象初始值设定项创建一个对象,分配描述您的属性(名字、姓氏、索引号、table 和成绩)。为计算平均成绩的对象分配一个方法

这是可行的解决方案,但不完全是应该完成的。

      function Grade (math, science, programming, management){
    this.math = math;
    this.science = science;
    this.programming = programming;
    this.management = management;

    return (math + science + programming + management)/arguments.length;
}

    

const student = {
        name: 'John',
        surname: 'Smith', 
        index: 'x4sx4sd',
        grade: Grade(5,4,5,5)
    }

console.log(student);

这是我的尝试,虽然行不通,但我认为仍然更接近事实,但没有平均部分

const student = {
        name: 'John',
        surname: 'Smith', 
        index: 'xxxxx',
        grade: 
        {
            math: 5,
            science: 5,
            language: 5,
            marketing: 5,
            management: 5

        },
        gradeAvg: function(grade){
            grade=this.grade;
            let total = 0;
            for (let value in object){
                total += grade[value]
            }
            return total;  
        }
    
    }

console.log(student);

我知道这是一个菜鸟问题,我已经尽我所能 google 但还是找到了任何东西,任何帮助将不胜感激。

将您的 gradeAvg 更改为 getter 函数,该函数将在您加载对象时执行。此外,要获得平均值(需要计数),您可以使用 Object.entries (将对象转换为数组)访问计数,然后获取长度

const student = {
  name: 'John',
  surname: 'Smith',
  index: 'xxxxx',
  grade: {
    math: 2,
    science: 5,
    language: 5,
    marketing: 1,
    management: 5
  },
  get gradeAvg() {
    let total = 0;
    for (let value in this.grade) {
      total += this.grade[value]
    }
    return total / Object.entries(this.grade).length;
  }
}

console.log(student);

因此,首先您需要将成绩对象从对象转换为数组,以便对所有元素求和。 Object.values does that, so {a: 1, b: 2} would become [1, 2]. Next you need to get the number of grades so you can then divide the sum to get the average. Last thing you need is a sum of the array we have created previously, reduce array method 用于将数组缩减为一个值。

        get GradeAvg() {
            const gradesArray = Object.values(this.grade);
            const gradesCount = gradesArray.length;
            const gradesSum = gradesArray.reduce((sum, current) => {
                sum += current;
                return sum;
            })

            return gradesSum / gradesCount;
        }