枚举TypeScript对象的属性

时间:2016-10-23 10:35:52

标签: javascript typescript iterator

鉴于以下课程,我如何枚举它的属性,即获得类似[station1, station2, station3 ...]的输出。我只能看到如何枚举属性的值,即[null, null, null]

class stationGuide {
    station1: any;
    station2: any;
    station3: any;

    constructor(){
        this.station1 = null;
        this.station2 = null;
        this.station3 = null;
     }
}

2 个答案:

答案 0 :(得分:72)

您有两种选择,使用Object.keys()然后forEach,或使用for/in

class stationGuide {
    station1: any;
    station2: any;
    station3: any;

    constructor(){
        this.station1 = null;
        this.station2 = null;
        this.station3 = null;
     }
}

let a = new stationGuide();
Object.keys(a).forEach(key => console.log(key));

for (let key in a) {
    console.log(key);
}

code in playground

答案 1 :(得分:0)

使用Reflect对象,您可以以编程方式访问和修改任何对象。这种方法也不会抛出“元素隐式具有'any'类型,因为类型'string'的表达式不能用于索引类型'{}'的错误”。

class Cat {
  name: string
  age: number

  constructor(name: string, age: number){
    this.name = name
    this.age = age
   }
}

function printObject(obj: any):void{
  const keys = Object.keys(obj)
  const values = keys.map(key => `${key}: ${Reflect.get(obj,key)}`)
  console.log(values)
}

const cat = new Cat("Fluffy", 5)
const dog = {
  name: "Charlie",
  age: 12,
  weight: 20
}

printObject(cat)
printObject(dog)

code in playground