[英]Javascript add object to constructor
Hello I'm trying to add a object to my Students array using a constructor,. 您好,我正在尝试使用构造函数向我的Student数组添加对象。
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. 在我的主要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])
];
But I want to add a new object later on, I thought I could just create a Student2
and then just Student1.push(Student2);
但是我想稍后再添加一个新对象,我想我可以先创建一个
Student2
,然后再创建Student1.push(Student2);
and then it would add the data to the Student1 array
. 然后将数据添加到
Student1 array
。 But I just get undefined [object Object]
when it's displaying the innerHTML
. 但是当它显示
innerHTML
时,我只是得到未定义的 [object Object]
。
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? 谁能帮助我将第三个对象放入
Student1
对象数组中?
Don't create a new array, just push the new Student to the Student1 array: 不要创建新的数组,只需将新的Student推送到Student1数组即可:
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: 您当前的代码将包含新学生的数组推到Student1数组上,因此Student1看起来像:
[
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]
. 几乎任何对象转换为字符串时都将显示
[object Object]
。 innerHTML
takes a String . innerHTML
采用String 。 You need to write an extra function to convert a Student into a 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.