循环js类的属性

时间:2014-01-11 08:49:28

标签: javascript loops properties

让我们说:

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

如何迭代属性?

类似的东西:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

for...in

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