2013-04-21 121 views
-1

爲什麼下面的JavaScript代碼不適合我?我應該在下面的代碼中做出什麼改變?在javascript中創建對象數組

function person(firstname, lastname, age, eyecolor) 
{ 
    this.firstname = firstname; 
    this.lastname = lastname; 
    this.age = age; 
    this.eyecolor = eyecolor; 
} 

for(var i = 0; i < 10; i++) 
{ 
    myFather[i] = new person("John", "Doe", i, "blue"); 
} 

for(var i = 0; i < 10; i++) 
{ 
    document.write(myFather[i].firstname + " is " + 
        myFather[i].age + " years old."); 
} 
+0

它是如何工作不適合你?任何錯誤消息?任何意外的結果? – Thilo 2013-04-21 06:55:44

+2

'ReferenceError:myFather未定義' – Musa 2013-04-21 06:56:42

+3

您將myFather初始化爲數組在哪裏? – ColinE 2013-04-21 06:56:46

回答

3

我看不到myFather正在任何地方被初始化。在將數組值分配給它之前,您需要這樣做。

var myFather = []; 
+0

'function person()'和'new person()'正在工作嗎? – 2013-04-21 07:15:41

+0

@MichelFeldheim:看起來沒問題 – Thilo 2013-04-21 07:16:55

1

myFather變量沒有被初始化:

var myFather = new Array();