gpt4 book ai didi

javascript - 如何组合对象并将其传输到类 w/es6 的数组

转载 作者:行者123 更新时间:2023-11-29 20:46:34 26 4
gpt4 key购买 nike

有必要编写一个类,其中包含针对学生的方法。让它成为任务 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 - 如何组合对象并将其传输到类 w/es6 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54317366/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com