在Typescript中循环枚举枚举的正确方法是什么? (目前使用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看起来像是枚举的索引号。
答案 0 :(得分:180)
两个选项:
selects
或者
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
字符串枚举看起来与常规枚举不同,例如:
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
编译成:
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"]
值(Object.keys(MyEnum);
):
["a", "b", "c"]
或使用Object.values():
Object.keys(MyEnum).map(key => MyEnum[key])