2017-02-21 37 views
1

我的代碼如下構造器與陣列和用於循環顯示錯誤

// 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); 
} 

唐,t無爲什麼,但它示出了下面

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

循環應該在'i Rajesh

+0

數組基於0。第一個索引= 0,最後一個索引=(長度 - 1) – Andreas

+0

其固定,謝謝@Rajesh –

回答

0
i <= family.length 

應該是

i < family.length 

因爲,陣列的indeces從零開始。因此,當您達到i的最大值時,陣列中不存在元素,因此undefined

+2

這應該是一個評論 – Rajesh

+1

@Rajesh Isn; t這解決了這個問題?簡短的回答並不意味着'評論' –

+1

不,這是一個答案。 –