打字稿:如何循环显示枚举值以便在单选按钮中显示?

时间:2016-09-07 14:35:35

标签: javascript arrays typescript enums element

在Typescript中循环枚举枚举的正确方法是什么? (目前使用typescrip 1.8.1)

我有以下枚举:

export enum MotifIntervention {
    Intrusion,
    Identification,
    AbsenceTest,
    Autre
}

export class InterventionDetails implements  OnInit
{
constructor( private interService: InterventionService )
{
    let i:number = 0;
    for (let motif in MotifIntervention) {
        console.log( motif );
    }
}

显示的结果是一个列表

0
1
2
3
Intrusion,
Identification,
AbsenceTest,
Autre

我确实只想在循环中进行4次迭代,因为枚举中只有4个元素,我不希望0 1 2和3看起来像是枚举的索引号。

1 个答案:

答案 0 :(得分:180)

两个选项:

selects

或者

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

code in playground

修改

字符串枚举看起来与常规枚举不同,例如:

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

编译成:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

这只是给你这个对象:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

您可以获得所有密钥({ A: "a", B: "b", C: "c" } ),如下所示:

["A", "B", "C"]

值(Object.keys(MyEnum); ):

["a", "b", "c"]

或使用Object.values()

Object.keys(MyEnum).map(key => MyEnum[key])