typescript 枚举对象的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40201970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Enumerate properties on an object
提问by George Edwards
Given the following class, how can I enumerate its properties, i.e. get an output like [station1, station2, station3 ...]
?
给定以下类,我如何枚举其属性,即获得类似的输出[station1, station2, station3 ...]
?
I can only see how to enumerate the values of the properties, i.e. [null, null, null]
.
我只能看到如何枚举属性的值,即[null, null, null]
.
class stationGuide {
station1: any;
station2: any;
station3: any;
constructor(){
this.station1 = null;
this.station2 = null;
this.station3 = null;
}
}
回答by Nitzan Tomer
You have two options, using the Object.keys()and then forEach, or use for/in:
您有两个选择,使用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);
}
(操场上的代码)
回答by szuuuken
With the Reflectobject you are able to to access and modify any object programmatically. This approach also doesn't throw a "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'" error.
使用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)
(操场上的代码)