簡體   English   中英

如何使用 es6 將對象組合和傳輸到類的數組

[英]how to combine and transfer objects to an array of a class w/ es6

有必要編寫一個包含對學生工作的方法的類。 讓它成為任務 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不應該擴展Student extends用於定義一個子類,它代表一個 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());

這將創建一個學生對象數組,並為您提供正確的輸出。

const students = [student1, student2]

首先,給大家一些建議! 學生不應擴展 Student 類。 這種遺產有不同的目的。 另外,我會重寫 Student 的方法,使其目標更加明確。

如果你想返回一個學生對象數組,我建議你循環/映射一個學生列表,然后為每個學生返回一個被推送到數組的格式化對象。

在 Student 類上,您還可以創建一個返回該格式化對象的方法,而不僅僅是循環/映射執行該方法的學生數組並將返回值推送到數組中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM