2013-01-03 57 views
1

下面是代碼:構造函數或數組或for循環出錯?

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

// Now we can make an array of peoples 
var family = new Array(); 
family[0] = Person("alice", 40); 
family[1] = Person("bob", 42); 
family[2] = Person("michelle", 8); 
family[3] = Person("timmy", 6); 

// loop through our new array 
for (i=0; i < family.length; i++;) { 
    console.log(family[i].name) 
}; 

這個腳本的預期成果是:

alice 
bob 
michelle 
timmy 

但輸出是:

Uncaught TypeError: Cannot read property 'name' of undefined (anonymous function)

回答

2

添加new關鍵字每個Person增加,並刪除for -loop中的額外;(在i++之後)

// 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 (i=0; i < family.length; i++) { 
    console.log(family[i].name);  // Also, added a semicolon here. Not required, but it's good practice to close your lines. 
}; 

現在,這將日誌:

alice
bob
michelle
timmy

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

console.info(family); 
// loop through our new array 
for (i=0; i < family.length; i++) { 
    console.log(family[i].name) 
}; 
+2

這是正確的,但你應該補充你改變了什麼,以及爲什麼一些評​​論。 – JJJ

0

我做了這樣的事情:

// Our Person constructor 
var Person = function(name,age) { 
    this.age = age; 
    this.name = name; 
}; 

// 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 famloop in family) { 
    console.log(family[famloop].name); 
}