【问题标题】:How can I loop through enum values for display in radio buttons? [duplicate]如何循环遍历枚举值以显示在单选按钮中? [复制]
【发布时间】:2017-01-15 07:35:08
【问题描述】:

在 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 看起来是枚举的索引号。

【问题讨论】:

标签: javascript arrays typescript enums element


【解决方案1】:

两种选择:

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)

【讨论】:

  • 它不起作用,因为 0 1 2 3 是字符串。
  • 这就是为什么要检查isNaN(Number(...))。它在我共享的操场上工作
  • 感谢这种方法。对于Object.keys 方法,您需要使用Object.keys(MotifIntervention).filter(key => isNaN(Number(key)))
  • 如果您希望循环遍历枚举类型的值,这将不起作用。所以如果typeof doThing 函数是(arg: MotifIntervention) => voidfor (let item in MotifIntervention) { doThing(item) } 将失败。这是因为for..in 循环会将item 视为string 类型,而不是MotifIntervention 类型。
  • @NitzanTomer - 这在运行时听起来像是一个很好的解决方法,但我说的是编译时间。当您尝试调用doThing(item) 并且doThing 的类型为(arg: MotifIntervention) => void 时,您将收到编译时错误“'string' 类型的参数不可分配给'MotifIntervention' 类型的参数。”
猜你喜欢
  • 2013-05-16
  • 1970-01-01
  • 2013-07-16
  • 2015-01-09
  • 1970-01-01
  • 2015-08-13
  • 1970-01-01
  • 2012-11-08
  • 2021-08-24
相关资源
最近更新 更多