枚举TypeScript对象的属性 [英] Enumerate properties on TypeScript Object

查看:88
本文介绍了枚举TypeScript对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Given the following class, how can I enumerate it's properties, i.e. get an output like [station1, station2, station3 ...]. I can only see how to enumerate the values of the properties, i.e. [null, null, null].

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

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


推荐答案

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

You have two options, using the Object.keys() and then forEach, or use 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);
}

操场上的代码

这篇关于枚举TypeScript对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆