javascript - 如何循环枚举值以在单选按钮中显示?

标签 javascript arrays typescript enums element

<分区>

在 TypeScript 中遍历枚举文字的正确方法是什么?

(我目前使用的是 TypeScript 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

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

关于javascript - 如何循环枚举值以在单选按钮中显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39372804/

相关文章:

arrays - 如何在 React + Typescript 中检查数组中 javascript 对象的所有值是否为真?

javascript - 如何将div的内容保存为图片?

javascript - 如何仅在特定选项上运行 jQuery

javascript - 使用 For 循环将 JS 数字转为文本

Python:打印所有以相同字母开头和结尾的名字

arrays - 解析数据并适应哈希给出了预期的结果

javascript - Aurelia - 自定义元素属性绑定(bind)解析

javascript - 如何在 javascript 中将子数组字符串数组转换为子数组数组?

javascript - 加快 iFrame 加载速度以避免验证错误

typescript - 指定参数类型为 T |为空但不为空