打字稿:如何循环枚举值在单选按钮中显示?(复制)

时间:2021-10-29 13:46:08

This question already has an answer here:

这个问题已经有了答案:

What is the proper way to loop through litterals of an enum in Typescript ? (Currently using typescrip 1.8.1)

在打字稿中循环遍历enum的正确方法是什么?(目前使用typescrip 1.8.1)

I've got the following 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 );
    }
}

The result displayed is a list

显示的结果是一个列表

0
1
2
3
Intrusion,
Identification,
AbsenceTest,
Autre

I do want only 4 iterations in the loop as there are only 4 elements in the enum, I don't want to have 0 1 2 and 3 that seem to be index numbers of the enum.

我只希望循环中有4个迭代,因为enum中只有4个元素,我不希望将0,1,2和3作为enum的索引号。

1 个解决方案

#1


68  

Two options:

两个选择:

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

Or

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

(code in playground)

在操场上(代码)


Edit

String enums look different than regular ones, for example:

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

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

Compiles into:

编译成:

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

Which just gives you this object:

它给了你这个物体:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

你可以像这样得到所有的钥匙(“A”、“B”、“C”):

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

及值(["a"、"b"、"c"):

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

Or using Object.values():

或者使用Object.values():

Object.values(MyEnum)

#1


68  

Two options:

两个选择:

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

Or

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

(code in playground)

在操场上(代码)


Edit

String enums look different than regular ones, for example:

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

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

Compiles into:

编译成:

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

Which just gives you this object:

它给了你这个物体:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

你可以像这样得到所有的钥匙(“A”、“B”、“C”):

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

及值(["a"、"b"、"c"):

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

Or using Object.values():

或者使用Object.values():

Object.values(MyEnum)