在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似乎是枚举的索引号。

最佳答案

两种选择:

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

要么

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.keys(MyEnum).map(key => MyEnum[key])

或使用Object.values():

Object.values(MyEnum)