我的代码如下
// Our Person constructor
function Person (name, age) {
this.name = name;
this.age = age;
}
// Now we can make an array of people
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);
// loop through our new array
for(var i = 0; i <= family.length; i++) {
console.log("My name is " + family[i].name);
}
唐,不是为什么,但它显示如下所示的错误
My name is alice
My name is bob
My name is michelle
My name is timmy
---
We're running a test below to make sure your code works.
My name is aliceMy name is bobMy name is michelleMy name is timmy
TypeError: family[i] is undefined
我无法纠正这个问题。请帮我解决。
答案 0 :(得分:0)
i <= family.length
应该是
i < family.length
因为,数组indeces从零开始。因此,当您达到i
的最大值时,数组中不存在元素,因此undefined