如何遍历枚举值以显示在单选按钮中? [英] How to loop through enum values for display in radio buttons?
本文介绍了如何遍历枚举值以显示在单选按钮中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Typescript中遍历枚举的正确方法是什么? (当前使用的类型为cripcrip 1.8.1)
What is the proper way to loop through litterals of an enum in Typescript ? (Currently using typescrip 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
我确实只希望循环中进行4次迭代,因为枚举中只有4个元素,我不想让0 1 2和3似乎是枚举的索引号.
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.
推荐答案
两个选项:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
或
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屋!
查看全文