【问题标题】:Javascript add object to constructorJavascript将对象添加到构造函数
【发布时间】:2014-03-27 12:08:30
【问题描述】:

您好,我正在尝试使用构造函数将对象添加到我的学生数组中。

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

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 时,我只会得到undefined [object Object]

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

谁能帮我把第三个对象放入Student1对象数组中?

【问题讨论】:

  • 这样做Student1.push(Student2); 你将一个数组推入一个数组。您应该直接推送它,例如:Student1.push(new Student(...));.

标签: javascript object constructor


【解决方案1】:

不要创建新数组,只需将新的 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
]

【讨论】:

    【解决方案2】:

    几乎所有Object在转换为String时都会显示[object Object]innerHTML 接受一个字符串。您需要编写一个额外的函数来将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
    

    【讨论】:

      猜你喜欢
      • 2017-04-25
      • 2014-04-22
      • 2021-05-16
      • 2013-10-27
      • 2019-04-22
      • 2019-04-20
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多