/*
//方向移动 - 非枚举实现方式
const UP = 0
const DOWN = 1
const LEFT = 2
const RIGHT = 3
let move = (direction: number): void => {
if (direction === UP) {
console.log("向上移动")
} else if (direction === DOWN) {
console.log("向下移动")
} else if (direction === LEFT) {
console.log("向左移动")
} else if (direction === RIGHT) {
console.log("向右移动")
}
}
move(UP)
*/
//枚举是用户自定义的类型, 由一组具有名称的常量组成, 枚举成员的值默认是从0开始自动递增
//"一组" 是指枚举类型中包含了多个成员, 每个成员都是一个常量
//定义一个枚举类型 Direction(方向)
enum Direction {
Up,
Down,
Left,
Right
}
console.log(Direction.Up, Direction.Down, Direction.Left, Direction.Right)
let move = (direction: Direction): void => { //使用枚举类型来定义 move 函数
if (direction === Direction.Up) {
console.log("向上移动")
} else if (direction === Direction.Down) {
console.log("向下移动")
} else if (direction === Direction.Left) {
console.log("向左移动")
} else if (direction === Direction.Right) {
console.log("向右移动")
}
}
move(Direction.Up)
//定义一个枚举类型 Permission(权限)
enum Permission {
Guest = 10, //显式指定值为10,其他枚举值则按顺序递增
Member,
Admin
}
console.log(Permission.Guest, Permission.Member, Permission.Admin)
//定义一个枚举类型 Color(颜色)
enum Color {
Red = "红",
Green = "绿",
Blue = "蓝"
}
console.log(Color.Red, Color.Green, Color.Blue)
9.枚举
-- 未经授权禁止转载 --
- 状态: 更新中
- 作者: 邓瑞
- 课时数量: 37 节课
更新中 ...