我有一个字符串枚举:
export enum TokenLength {
SIX = '6',
EIGHT = '8',
}
我需要得到字符串' SIX'奥德'八,'所以反向映射这个枚举。 我尝试过多种方法:
tokenLength = TokenLength;
for (var enumMember in this.tokenLength) {
console.log("enum member: ", enumMember); //result: enum member: SIX , enum member: EIGHT
}
for (var enumMember in this.tokenLength) {
console.log("enum member: ", this.tokenLength[enumMember]); //result: enum member: 6, enum member: 8
}
这似乎工作正常,但每当我执行以下操作时,它都无法正常工作。
console.log(this.tokenLength['SIX']); //result: 6
console.log(this.tokenLength.SIX); //result: 6
console.log(this.tokenLength[this.tokenLength.SIX]); //result: undefined
console.log(this.tokenLength['6']); //result: undefined
console.log(this.tokenLength[0]); //result: undefined
我需要' undefined'结果是' SIX'我怎样才能做到这一点?提前谢谢。
答案 0 :(得分:0)
您可以查看打字稿文档。typescript
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/left_rounded"
android:backgroundTint="@color/red"
android:text="@string/lang_en"
android:textColor="@color/white"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/right_rounded"
android:text="@string/lang_ar" />
要使其以这种方式工作,您必须删除枚举中的引号:
enum Enum {
A
}
let a = Enum.A;
let nameOfA = Enum[a]; // "A"
希望有所帮助
答案 1 :(得分:0)
答案已经存在 https://stackoverflow.com/a/18112157/7771064
for (var size in TokenLength) {
if (!parseInt(size))
console.log(size);
}
答案 2 :(得分:0)
答案 3 :(得分:0)
function getTokenLength(value: string): TokenLength | undefined {
const keys = Object.keys(TokenLength);
const values = keys.map(k => TokenLength[k as any]);
const index = values.indexOf(value);
return index > -1 ? TokenLength[index] as TokenLength: undefined;
}