有必要写一个带有学生学习方法的课程。让它成为任务1。接下来,我需要编写另一个类,该类将包含数组中任务1的对象。
据我了解,应该出现[{name:''...},{name:``}}]之类的东西
但是如何正确编写它,我只是听不懂或者我很愚蠢

是否可以立即创建带有对象的数组,或者这是通过方法完成的?



class Student {
  constructor(fName, lName, birth, marks) {
    this.fName = fName;
    this.lName = lName;
    this.birth = birth;
    this.marks = marks;
    this.attendance = [];

  }
  midAttendance() {
    var count = 0;
    var sum = 0;
    for (var i = 0; i < this.attendance.length; i++) {
      if (this.attendance[i] === 'true') {
        count++;
        sum++;
      } else {
        sum++;
      }
    }
    return count / sum;
  }

  getAge() {
    return new Date().getFullYear() - this.birth;
  }
  midMark() {
    var count = 0;
    var sum = 0;
    for (var i = 0; i < this.marks.length; i++) {
      count++;
      sum += this.marks[i];
    }
    return (sum / count);
  }
  present() {
    if (this.attendance.length < 25) {
      this.attendance.push('true');
    } else {
      alert("full")
    };
  }
  absent() {
    if (this.attendance.length < 25) {
      this.attendance.push('false');
    } else {
      alert("full")
    };
  }
  summary() {
    var mMark = this.midMark();
    var mAttendance = this.midAttendance();
    if (mMark > 90 && mAttendance > 0.9) {
      return "molodec";
    } else if ((mMark > 90 && mAttendance <= 0.9) || (mMark <= 90 && mAttendance > 0.9)) {
      return "norm";
    } else {
      return "rediska";
    }
  }
}

class Students extends Student {
  constructor() {
    super(fName, lName, birth, marks);
  }
  let arr = [];
  getStudents() {

  }
}

let student1 = new Student('alex', 'petrov', '1999', [90, 94, 91, 91, 90]);
let student2 = new Student('vova', 'ivanov', '1994', [2, 3, 4, 3, 5]);

最佳答案

Students不应扩展Studentextends用于定义代表IS-A关系的子类。但是学生名单并不是一种学生。

Students应该是一个完全独立的类,例如

class Students {
    constructor() {
        this.arr = [];
    }
    addStudent(s) {
        this.arr.push(s);
    }
    removeStudent(s) {
        let index = this.arr.indexOf(s);
        if (index > -1) {
            this.arr.splice(index, 1);
        }
    }
    getStudents() {
        return this.arr.slice(); // make a copy so they can't modify the actual array
    }
}


然后,您可以执行以下操作:

let class = new Students;
class.addStudent(student1);
class.addStudent(student2);
console.log(class.getStudents());

关于javascript - 如何将对象组合并转移到带有es6的类的数组中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54317366/

10-13 05:58