简体   繁体   中英

Javascript add object to constructor

Hello I'm trying to add a object to my Students array using a constructor,.

This would be my Student constructor.

var Student = function (name, address, city, state, gpa) {
    this.name = name;
    this.address = address;
    this.city = city;
    this.state = state;
    this.gpa = gpa;
    console.log(name, address, city, state, gpa);
};

In my main js I would call and add the objects like so.

var Student1 = [
    new Student("Some Guy","Some address","some city","some state",[2.5,3.1,4.0]),
    new Student("Some Guy","Some address","some city","some state",[2.5,3.1,4.0])
];

But I want to add a new object later on, I thought I could just create a Student2 and then just Student1.push(Student2); and then it would add the data to the Student1 array . But I just get undefined [object Object] when it's displaying the innerHTML .

var Student2 = [
    new Student("Some Guy","Some address","some city","some state",[2.5,3.1,4.0])
];
Student1.push(Student2);

Can anyone help me get this third object into the Student1 object array?

Don't create a new array, just push the new Student to the Student1 array:

Student1.push(new Student("Some Guy","Some address","some city","some state",2.5,3.1,4.0]));

Your current code is pushing an array containing the new student onto the Student1 array, so Student1 would look like:

[
    studentInstance1,
    studentInstance2,
    [
        studentInstance3
    ]
]

By changing to push only the new object, not an array, it now looks like:

[
    studentInstance1,
    studentInstance2,
    studentInstance3
]

Almost any Object when converted to a String will display [object Object] . innerHTML takes a String . You need to write an extra function to convert a Student into a String .

Student.prototype.toString = function () {
    return 'Student: ' + this.name; // etc
};

({}) + '';               // "[object Object]", normal object toString
new Student('Bob') + ''; // "Student: Bob", from our toString function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM