enum Color {Red, Green, Blue};
let c: Color = Color.Blue;
console.log(c); // 输出 2
//命令行编译
tsc hello.ts
得到如下 js 代码:
var Color;
(function (Color) {
Color[Color["Red"] = 0] = "Red";
Color[Color["Green"] = 1] = "Green";
Color[Color["Blue"] = 2] = "Blue";
})(Color || (Color = {}));
;
var c = Color.Blue;
console.log(c); // 输出 2
乍一看,有点懵。为便于理解,改写如下:
var Color;
if(!Color){
Color={};
}
function constructEnum(Color){
Color["Red"]=0;
Color[0]="Red";
Color["Green"]=1;
Color[1]="Green";
Color["Blue"]=2;
Color[2]="Blue";
}
constructEnum(Color);
var c=Color.Blue;
console.log(c); // 输出 2
输出看看:
console.log(Color);
//命令行执行
node hello.js
输出结果如下:
{ '0': 'Red', '1': 'Green', '2': 'Blue', Red: 0, Green: 1, Blue: 2 }