[英]Javascript add object to constructor
您好,我正在尝试使用构造函数向我的Student数组添加对象。
这将是我的学生构造函数。
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
。 但是当它显示innerHTML
时,我只是得到未定义的 [object Object]
。
var Student2 = [
new Student("Some Guy","Some address","some city","some state",[2.5,3.1,4.0])
];
Student1.push(Student2);
谁能帮助我将第三个对象放入Student1
对象数组中?
不要创建新的数组,只需将新的Student推送到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
]
几乎任何对象转换为字符串时都将显示[object Object]
。 innerHTML
采用String 。 您需要编写一个额外的函数将Student转换为String 。
Student.prototype.toString = function () {
return 'Student: ' + this.name; // etc
};
({}) + ''; // "[object Object]", normal object toString
new Student('Bob') + ''; // "Student: Bob", from our toString function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.