本文介绍了枚举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;
     }
}


推荐答案

你有两种选择,使用然后,或者使用:

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对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 14:29