我想迭代一个TypeScript枚举对象,并获得每个枚举符号名称,例如: enum myEnum {entry1, entry2}
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
我想迭代一个TypeScript枚举对象,并获得每个枚举符号名称,例如: enum myEnum {entry1, entry2}
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
当前回答
对我来说,一个更简单、实用和直接的方法来理解正在发生的事情,就是下面的列举:
enum colors { red, green, blue };
本质上将转换为:
var colors = { red: 0, green: 1, blue: 2,
[0]: "red", [1]: "green", [2]: "blue" }
正因为如此,以下情况将是正确的:
colors.red === 0
colors[colors.red] === "red"
colors["red"] === 0
这创建了一个简单的方法来获取枚举的名称,如下所示:
var color: colors = colors.red;
console.log("The color selected is " + colors[color]);
它还创建了一种将字符串转换为枚举值的好方法。
var colorName: string = "green";
var color: colors = colors.red;
if (colorName in colors) color = colors[colorName];
以上两种情况更为常见,因为通常您对特定值的名称和以通用方式序列化值更感兴趣。
其他回答
这个解决方案也可以。
enum ScreenType {
Edit = 1,
New = 2,
View = 4
}
var type: ScreenType = ScreenType.Edit;
console.log(ScreenType[type]); //Edit
这对于基于键值的enum更有效:
enum yourEnum {
["First Key"] = "firstWordValue",
["Second Key"] = "secondWordValue"
}
Object.keys(yourEnum)[Object.values(yourEnum).findIndex(x => x === yourValue)]
// Result for passing values as yourValue
// FirstKey
// SecondKey
在TypeScript中,一个enum在javascript中被编译成一个map(从键中获取值):
enum MyEnum {
entry0,
entry1,
}
console.log(MyEnum['entry0']); // 0
console.log(MyEnum['entry1']); // 1
它还创建了一个反向映射(从值中获取键):
console.log(MyEnum[0]); // 'entry0'
console.log(MyEnum[0]); // 'entry1'
所以你可以通过以下方式访问一个条目的名称:
console.log(MyEnum[MyEnum.entry0]); // 'entry0'
console.log(MyEnum[MyEnum.entry1]); // 'entry1'
但是,string enum在设计上没有反向映射(参见注释和pull request),因为这可能导致映射对象中的键和值之间的冲突。
enum MyEnum {
entry0 = 'value0',
entry1 = 'value1',
}
console.log(MyEnum['value0']); // undefined
console.log(MyEnum['value1']); // undefined
如果你想强制你的字符串enum编译一个反向映射(你必须确保所有的键和值都是不同的),你可以使用这个技巧:
enum MyEnum {
entry0 = <any>'value0',
entry1 = <any>'value1',
}
console.log(MyEnum['value0']); // 'entry0'
console.log(MyEnum['value1']); // 'entry1'
console.log(MyEnum[MyEnum.entry0]); // 'entry0'
console.log(MyEnum[MyEnum.entry1]); // 'entry1'
要获得枚举值的列表,您必须使用:
enum AnimalEnum {
DOG = "dog",
CAT = "cat",
MOUSE = "mouse"
}
Object.values(AnimalEnum);
从TypeScript 2.4开始,枚举可以包含字符串初始化器https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html
这允许你这样写:
enum Order {
ONE = "First",
TWO = "Second"
}
console.log(`One is ${Order.ONE.toString()}`);
得到这样的输出:
一个是First