在javascript中创建一个对象数组

时间:2013-04-21 06:54:30

标签: javascript json

为什么下面的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.");
}

2 个答案:

答案 0 :(得分:3)

我没有看到myFather在任何地方被初始化。在将数组值分配给它之前,您需要这样做。

var myFather = [];

答案 1 :(得分:1)

myFather变量未初始化:

var myFather = new Array();