试图访问数组:family [i]未定义

时间:2015-11-25 03:14:05

标签: javascript arrays

我试图按顺序打印每个人的姓名,但我一直收到此错误family[i] is undefined

function Person (name, age) {
    this.name = name;
    this.age = age;
}

var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);

for(var i = 0; i <= family.length; i++) {
    console.log(family[i].name);
}

2 个答案:

答案 0 :(得分:1)

您的for循环超出了数组的范围。尝试:

for( var i = 0; i < family.length; i++ )

请记住,array.length将始终高于最大数组索引,因为索引从0开始,而length从1开始。

答案 1 :(得分:0)

在尝试读取末尾的未定义值时,按如下方式编辑for循环:

for(var i = 0; i <= family.length; i++) {
    console.log(family[i].name);
}

for(var i = 0; i < family.length; i++) {
    console.log(family[i].name);
}