如何遍历枚举值以显示在单选按钮中? [英] How can I loop through enum values for display in radio buttons?
本文介绍了如何遍历枚举值以显示在单选按钮中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在TypeScript中循环遍历枚举的正确方法是什么?
What is the proper way to loop through literals of an enum in TypeScript?
(我目前正在使用TypeScript 1.8.1)
(I am currently using 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似乎是枚举的索引号。
I do want only four iterations in the loop as there are only four elements in the enum. I don't want to have 0 1 2 and 3 that seem to be index numbers of the enum.
推荐答案
两个选项:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
(操场上的代码)
字符串枚举看起来与常规枚举不同,例如:
String enums look different than regular ones, for example:
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]
)像这样:
You can get all the keys (["A", "B", "C"]
) like this:
Object.keys(MyEnum);
和值( [ a, b, c ]
):
Object.keys(MyEnum).map(key => MyEnum[key])
或使用 Object.values():
Object.values(MyEnum)
这篇关于如何遍历枚举值以显示在单选按钮中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文