TypeScript入门4:枚举

enum Season {
  SPRING,
  SUMMER,
  AUTUMN,
  WINTER
}

let spring:Season = Season.SPRING;
console.log(spring); //0
console.log(typeof spring); //number
console.log(Season[spring]);  //SPRING

//ts中 枚举实际上是⼀个对象,⽽每个枚举值都是该对象的⼀个属性,并且每个属性都有具体的值,属性值只⽀持两种类型:数字或字符串
//默认情况下,每个属性的值都是数字,并且从 0 开始递增

enum Direction {
  UP,
  BOTTOM,
  LEFT,
  RIGHT
}
console.log(Direction.UP) //0
console.log(Direction.BOTTOM) //1
console.log(Direction.LEFT) //2
console.log(Direction.RIGHT) //3

/**
 * 根据指定的方向进行移动。
 * @param direction 移动的方向,是Direction枚举类型的一个值。
 * 该函数没有返回值。
 * 根据方向变量的值,选择不同的移动方式并打印出来
 */
function move(direction: Direction) {
  if(direction===Direction.UP){
    console.log('向上移动');
  }else if(direction===Direction.BOTTOM){
    console.log('向下移动');
  }else if(direction===Direction.LEFT){
    console.log('向左移动');
  }else{
    console.log('向右移动');
  }
}
move(Direction.UP);

//除了使⽤默认的数字作为属性的值,我们还能⼿动为每个属性赋值

enum Direction2 {
  UP = 11,
  BOTTOM = 22,
  LEFT = 33,
  RIGHT = 44
}
console.log(Direction2.UP) //11
console.log(Direction2.BOTTOM) //22
console.log(Direction2.LEFT) //33
console.log(Direction2.RIGHT) //44


enum Direction3 {
  UP = 'up',
  BOTTOM = 'bottom',
  LEFT = 'left',
  RIGHT = 'right'
}
console.log(Direction3.UP) //up
console.log(Direction3.BOTTOM) //bottom
console.log(Direction3.LEFT) //left
console.log(Direction3.RIGHT) //right


enum Color {
  Red = 0xFF0000,
  Green = 0x00FF00,
  Blue = 0x0000FF
}
  
enum FontSize {
  Small = 12,
  Medium = 16,
  Large = 20,
  ExtraLarge = 24
}
 
posted @ 2024-04-30 14:31  yub4by  阅读(4)  评论(0编辑  收藏  举报