Javascript 打字稿:如何遍历枚举值以显示在单选按钮中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39372804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript : how to loop through enum values for display in radio buttons?
提问by Anthony Brenelière
What is the proper way to loop through litterals of an enum in Typescript ? (Currently using typescrip 1.8.1)
在 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 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 次迭代,因为枚举中只有 4 个元素,我不希望 0 1 2 和 3 似乎是枚举的索引号。
回答by Nitzan Tomer
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:
您可以["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)