const AnimeState = Object.freeze({
Idle = 1,
Walking=2,
Running=3,
Attacking = 4,
Dead = 0,
Uninitialized: -1
});
this.state = AnimeState.Uninitialized
试图获取名称状态的,console.log(AnimeState[this.state])
,这行不通,可能是因为我用了Object.freeze()
的方法。有没有一种方法可以同时得到两个世界?
欲望:console.log(AnimeState[this.state])
if state === AnimeState.Uninitialized
,给我Uninitialized
作为string
。
我遵循这个链接:如何获得枚举项的名称?在那里,他们指出:
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]);
代码的问题是,您试图使用赋值操作符(=)而不是冒号(:)来定义AnimeState
对象的属性值。而且,您正在使用camelCase
而不是PascalCase
作为属性名称。
你可以试试下面的代码:
const AnimeState = Object.freeze({
IDLE: 1,
WALKING: 2,
RUNNING: 3,
ATTACKING: 4,
DEAD: 0,
UNINITIALIZED: -1
});
let state = AnimeState.UNINITIALIZED;
console.log(Object.keys(AnimeState).find(key => AnimeState[key] === state));
如果您指定对象为enum
:
enum AnimeState {
UNINITIALIZED = -1,
DEAD = 0,
IDLE = 1,
WALKING = 2,
RUNNING = 3,
ATTACKING = 4,
}
然后像这样赋值给state:
let state: AnimeState = AnimeState.UNINITIALIZED;