如何循环遍历枚举值以在单选按钮中显示

How can I loop through enum values for display in radio buttons?

本文关键字:单选按钮 显示 枚举 遍历 何循环 循环      更新时间:2023-09-26

在TypeScript中循环遍历枚举字面值的正确方法是什么?

(我现在使用的是TypeScript 1.8.1)

我有以下enum:

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

我确实希望在循环中只进行四次迭代,因为枚举中只有四个元素。我不想让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])));

(code in playground)


编辑

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

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)