Home > Software design >  Cant seem to push an object into an array
Cant seem to push an object into an array

Time:07-15

class Member {
    constructor(name, type, joindate, dob, points) {
        this.name = name;
        this.type = type;
        this.joindate = joindate;
        this.dob = dob;
        this.points = points;
    }
    ListInfo() {
        return this.name   "\n"   this.type   "\n"   this.joindate   "\n"   this.dob   "\n"   this.points   "\n";
    }
}

class MemberGroup {
    constrctor() {
        this.List = [];
    }
}

//Member Infos
var Members = new MemberGroup();
Members.List.push(new Member("Leonardo", "Gold", "1 Dec 2019", "1 Jan 1980", 1400));

I have checked and this code is definitely syntax valid, no idea where went wrong or what went wrong I just cant seem to push values into the array.

CodePudding user response:

Change it to:

class Member {
    constructor(name, type, joindate, dob, points) {
        this.name = name;
        this.type = type;
        this.joindate = joindate;
        this.dob = dob;
        this.points = points;
    }
    ListInfo() {
        return this.name   "\n"   this.type   "\n"   this.joindate   "\n"   this.dob   "\n"   this.points   "\n";
    }
}

class MemberGroup {
    List = []
}

//Member Infos
var Members = new MemberGroup();
Members.List.push(new Member("Leonardo", "Gold", "1 Dec 2019", "1 Jan 1980", 1400));
console.log(Members.List);

You need to declare the var otherwise you can't find it.

CodePudding user response:

It works, just fix constrctor to constructor in the MemberGroup class. I changed nothing else.

class Member {
    constructor(name, type, joindate, dob, points) {
        this.name = name;
        this.type = type;
        this.joindate = joindate;
        this.dob = dob;
        this.points = points;
    }
    ListInfo() {
        return this.name   "\n"   this.type   "\n"   this.joindate   "\n"   this.dob   "\n"   this.points   "\n";
    }
}

class MemberGroup {
    constructor() {  // Fix this typo
        this.List = [];
    }
}

//Member Infos
var Members = new MemberGroup();
Members.List.push(new Member("Leonardo", "Gold", "1 Dec 2019", "1 Jan 1980", 1400));
console.log(Members.List)

  • Related