在TypeScript中循环枚举的字面量的正确方法是什么?
(我目前使用的是TypeScript 1.8.1。)
我有以下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);
}
}
显示的结果是一个列表
0
1
2
3
Intrusion,
Identification,
AbsenceTest,
Autre
我只想在循环中进行四次迭代,因为枚举中只有四个元素。我不想让0 1 2和3看起来像是enum的索引号。
两个选择:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
(操场上的代码)
Edit
字符串枚举看起来与常规枚举不同,例如:
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.keys(MyEnum).map(key => MyEnum[key])
或者使用Object.values():
Object.values(MyEnum)
两个选择:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
(操场上的代码)
Edit
字符串枚举看起来与常规枚举不同,例如:
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.keys(MyEnum).map(key => MyEnum[key])
或者使用Object.values():
Object.values(MyEnum)