枚举类型的枚举值默认是1, 2, 3

  1. enum Direction {
  2. up,
  3. down,
  4. left,
  5. right,
  6. }
  7. console.log(Direction.down); // 1
  8. console.log(Direction[0]); // 这个值反解回来就是"up"这个字符串

自定义枚举值

  1. enum Direction {
  2. up = "a",
  3. down = "b",
  4. left = "c",
  5. right = "d",
  6. }
  7. console.log(Direction.down); // a
  8. console.log(Direction["a"]); // up
  9. console.log(Direction["a"] === "up"); // true

常量枚举

常量枚举可以提升性能, 但是不能反解

  1. const enum Direction {
  2. up,
  3. down,
  4. left,
  5. right,
  6. }
  7. console.log(Direction.down);
  8. console.log(Direction[1]);

image.png