枚举对象的属性

给定以下类,我如何枚举它的属性,即获得类似 [station1, station2, station3 ...]的输出?

我只能看到如何枚举属性的值,即 [null, null, null]

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


constructor(){
this.station1 = null;
this.station2 = null;
this.station3 = null;
}
}
94850 次浏览

您有两种选择,使用 Key (),然后使用 为每个人,或者使用 入境事务处:

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

(操场上的密码)

使用 反思对象,您能够以编程方式访问和修改任何对象。此方法也不会抛出“ Element 隐式具有‘ 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)

(操场上的密码)