2014-03-27 76 views
0

你好,我正在嘗試使用構造函數將一個對象添加到我的Students數組中。Javascript將對象添加到構造函數中

這將是我的學生構造函數。

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。但是我只是得到undefined[object Object]當它顯示innerHTML

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

誰能幫我把這個第三個對象爲Student1對象數組?

+0

這樣做'Student1.push(Student2);'你將數組推到一個數組中。你應該直接推它,如:'Student1.push(新生(...));'。 – DontVoteMeDown

回答

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 
] 
+0

非常感謝! – user3468440

0

幾乎任何對象轉換爲字符串將顯示[object Object]innerHTML需要字符串。您需要額外編寫一個函數學生轉換爲字符串

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

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

不知道,謝謝分享! – user3468440

相關問題