当我console.log时,此代码:

 var Student = function(name, address, gpa){

    console.log(this);
    this.name = name;
    this.address = address;
    this.gpa = gpa;

    console.log("name is equal to " + name);
    console.log("address is equal to " + address);
    console.log("gpa is equal to " + gpa);
};



    var studentCall = [
    new Student ({
        name: "Marshae Hannor",
        address:{
            street: "345 Main St",
            city: "Smyrna",
            state: "GA"},
        gpa: [2.5, 3.5, 4.0]}),
    new Student ({
        name: "Vernon Owens",
        address:{
            street: "439 Serious St",
            city: "Baltimore",
            state: "MD"},
        gpa: [3.5, 3.2, 3.7]})
];


这是我在console.log中得到的

对象{}
main2.js(第39行)
名称等于[object Object]
main2.js(第44行)
地址等于未定义
main2.js(第45行)
gpa等于未定义
main2.js(第46行)
对象{}
main2.js(第39行)
名称等于[object Object]
main2.js(第44行)
地址等于未定义
main2.js(第45行)
gpa等于未定义

有人可以帮助我了解我在做什么错误。谢谢

最佳答案

在对Student的调用中,您传递了一个参数,该参数是一个看起来像这样的对象:

{
    name: "Marshae Hannor",
    address:{
        street: "345 Main St",
        city: "Smyrna",
        state: "GA"},
    gpa: [2.5, 3.5, 4.0]
}


但是您的Student函数希望接收三个离散参数。因此,您可以在没有{}且没有给出参数名称的情况下调用它:

var studentCall = [
    new Student (
        "Marshae Hannor",
        {
            street: "345 Main St",
            city: "Smyrna",
            state: "GA"},
        [2.5, 3.5, 4.0]),
    new Student (
        "Vernon Owens",
        {
            street: "439 Serious St",
            city: "Baltimore",
            state: "MD"},
        [3.5, 3.2, 3.7])
];


或者,修改Student以期望仅接收具有这些属性的单个对象:

var Student = function(obj){

    console.log(this);
    this.name = obj.name;
    this.address = obj.address;
    this.gpa = obj.gpa;

    console.log("name is equal to " + this.name);
    console.log("address is equal to " + this.address);
    console.log("gpa is equal to " + this.gpa);
};

关于javascript - 在构造函数中的数组中的对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20025811/

10-15 17:52