0

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?

1
  • Doing this Student1.push(Student2); you're pushing an array into an array. You should push it directly, like: Student1.push(new Student(...));. Commented Mar 27, 2014 at 12:12

2 Answers 2

1

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
]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.