Javascript将对象添加到构造函数

时间:2014-03-27 12:08:30

标签: javascript object constructor

您好我尝试使用构造函数将对象添加到Students数组中。

这将是我的学生构造函数。

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);
};

在我的主要js中,我会调用并添加这样的对象。

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])
];

但是我想稍后添加一个新对象,我想我可以创建一个Student2,然后只需Student1.push(Student2);然后将数据添加到Student1 array。但是当我显示[object Object]时,我只是 undefined innerHTML

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

任何人都可以帮我把第三个对象放到Student1对象数组中吗?

2 个答案:

答案 0 :(得分:1)

不要创建新数组,只需将新学生推送到Student1数组:

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

您当前的代码正在将包含新学生的数组推送到Student1数组,因此Student1将如下所示:

[
    studentInstance1,
    studentInstance2,
    [
        studentInstance3
    ]
]

通过更改为仅推送新对象而不是数组,它现在看起来像:

[
    studentInstance1,
    studentInstance2,
    studentInstance3
]

答案 1 :(得分:0)

转换为 String 时,几乎所有 Object 都会显示[object Object]innerHTML获取字符串。您需要编写额外的函数以将学生转换为 String

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

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