09枚举类型
# 枚举类型
枚举类型是很多语言都拥有的类型,它用于声明一组命名的常数,当一个变量有几种可能的取值时,可以将它定义为枚举类型。
# 1、数字枚举
当我们声明一个枚举类型是,虽然没有给它们赋值,但是它们的值其实是默认的数字类型,而且默认从0开始依次累加。
enum color{
blue,
red,
green
}
console.log(color.blue === 0)//true
console.log(color.red === 1)//true
console.log(color.green === 2)//true
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
赋值第一个值之后,后面的值会进行累加
enum color{
blue = 10,
red,
green
}
console.log(color.blue)//10
console.log(color.red)//11
console.log(color.green)//12
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 2、字符串枚举
值也可以是字符串。
enum color{
blue = 'blue',
red = 'red',
green = 'green'
}
console.log(color.blue)//blue
console.log(color.red)//red
console.log(color.green)//green
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 3、异构枚举
值可以是不同类型的数据。
enum color{
blue = 0,
red = 'red',
green = 1
}
console.log(color.blue)//0
console.log(color.red)//red
console.log(color.green)//1
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 4、反向映射
enum color{
blue,
red,
green
}
console.log(color[0])//blue
console.log(color[1])//red
console.log(color[2])//green
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
编辑 (opens new window)
上次更新: 2023/08/06, 00:38:41