如何遍历枚举值以在单选按钮中显示? [英] How can I loop through enum values for display in radio buttons?
问题描述
在 TypeScript 中循环遍历枚举的文字的正确方法是什么?
(我目前使用的是 TypeScript 1.8.1.)
我有以下枚举:
export enum MotifIntervention {入侵,鉴别,缺勤测试,奥特雷}导出类 InterventionDetails 实现 OnInit{构造函数(私有interService:InterventionService){让我:数字= 0;for(让 MotifIntervention 中的主题){控制台日志(主题);}}
显示的结果是一个列表
<预><代码>0123入侵,鉴别,缺勤测试,奥特雷我只想要循环中的四次迭代,因为枚举中只有四个元素.我不想让 0 1 2 和 3 看起来像是枚举的索引号.
两个选项:
for(让项目在 MotifIntervention){如果 (isNaN(Number(item))) {控制台日志(项目);}}
或
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
(操场上的代码)
<小时>编辑
字符串枚举看起来与常规枚举不同,例如:
enum MyEnum {A = "a",B = "b",C = "c"}
编译成:
var MyEnum;(功能(MyEnum){MyEnum["A"] = "a";MyEnum["B"] = "b";MyEnum["C"] = "c";})(MyEnum || (MyEnum = {}));
这只是给你这个对象:
<代码>{答:一个",乙:乙",丙:c"}
你可以像这样得到所有的键 (["A", "B", "C"]
):
Object.keys(MyEnum);
和值 (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
或者使用 Object.values():
Object.values(MyEnum)
What is the proper way to loop through literals of an enum in TypeScript?
(I am currently using TypeScript 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 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.
Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
Edit
String enums look different than regular ones, for example:
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:
Object.keys(MyEnum);
And the values (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
这篇关于如何遍历枚举值以在单选按钮中显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!