枚举对象的属性 [英] Enumerate properties on an object

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

问题描述

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

Given the following class, how can I enumerate its properties, i.e. get an output like [station1, station2, station3 ...]?

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

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

推荐答案

您可以使用

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

( 查看全文

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