2014-01-11 18 views
0

讓說的屬性:環路一個js類

function person(){ 
    this.name = null; 
    this.lastname = null; 
    this.age = null; 
    this.height = null; 
} 

我怎樣才能通過屬性迭代?

喜歡的東西:

foreach(properties as property){ 
    console.log (property.nameoftheproperty, property.valueoftheproperty); 
} 
+0

嘗試'for(var x in person){x,person [x]}'或'Object.keys(person)' – exebook

回答

2

您可以使用for..in循環,這樣

function Person(){ 
    this.name = null; 
    this.lastname = null; 
    this.age = null; 
    this.height = null; 
} 

var person = new Person(); 
for (var key in person) { 
    console.log(key, person[key]); 
} 

輸出

name null 
lastname null 
age null 
height null 
0

for...in

for(var prop in properties) { 
    console.log(properties[prop]); 
}