前端枚举

  目录

前端枚举的简单入门

枚举在类似java等语言中很基础,但是js中却没有,即使现在的es6也没有把枚举加进来。但是,typescript中是有枚举供使用的。

typescript中枚举示例

demo1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// ts
enum demo1 {
Up = 1,
Down,
Left,
Right
}

// js
var demo1;
(function (demo1) {
demo1[demo1["Up"] = 1] = "Up";
demo1[demo1["Down"] = 2] = "Down";
demo1[demo1["Left"] = 3] = "Left";
demo1[demo1["Right"] = 4] = "Right";
})(demo1 || (demo1 = {}));

// console
{
"1": "Up",
"2": "Down",
"3": "Left",
"4": "Right",
"Up": 1,
"Down": 2,
"Left": 3,
"Right": 4
}

demo2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// ts
enum demo2 {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}

// js
var demo2;
(function (demo2) {
demo2["Up"] = "UP";
demo2["Down"] = "DOWN";
demo2["Left"] = "LEFT";
demo2["Right"] = "RIGHT";
})(demo2 || (demo2 = {}));

// console
{
"Up": "UP",
"Down": "DOWN",
"Left": "LEFT",
"Right": "RIGHT"
}

demo3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// ts
enum demo3 {
No = 0,
Yes = "YES",
}

// js
var demo3;
(function (demo3) {
demo3[demo3["No"] = 0] = "No";
demo3["Yes"] = "YES";
})(demo3 || (demo3 = {}));

// console
{
"0": "No",
"No": 0,
"Yes": "YES"
}

上面3个例子,ts部分是在typescript中的写法,js部分是typescript编译后的写法。可以发现,枚举中的数字类型和字符串类型编译后的结果稍有区别,在使用时也可以灵活使用。

前端中枚举的作用

不难看出,枚举被编译后的结果就是一个js对象,那直接使用对象不是更好?
其实,枚举主要作用是减少代码的错误,比如这样一段代码:

1
2
3
4
5
6
7
8
9
10
11
enum demo {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}

// 使用1
demo.Up
// 使用2
demo.Upp

上述代码的使用2,在编译阶段就会报错,如果不使用ts的话,只能在运行时才能发现错误,可以提高代码正确率。

实际应用

vue3的源码中:

1
2
3
4
5
6
7
8
9
10
11
12
13
export const enum ShapeFlags {
ELEMENT = 1,
FUNCTIONAL_COMPONENT = 1 << 1,
STATEFUL_COMPONENT = 1 << 2,
TEXT_CHILDREN = 1 << 3,
ARRAY_CHILDREN = 1 << 4,
SLOTS_CHILDREN = 1 << 5,
TELEPORT = 1 << 6,
SUSPENSE = 1 << 7,
COMPONENT_SHOULD_KEEP_ALIVE = 1 << 8,
COMPONENT_KEPT_ALIVE = 1 << 9,
COMPONENT = ShapeFlags.STATEFUL_COMPONENT | ShapeFlags.FUNCTIONAL_COMPONENT
}

这样一段代码,简单些理解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const study =  {
html: 1,
css: 1 << 1,
js: 1 << 2,
svg: 1 << 3,
canvas: 1 << 4
}
function isStudy(studentNum, ...enumStudyArr) {
// 1 00000001 代表html
// 2 00000010 代表css
// 4 00000100 代表js
// 8 00001000 代表svg
// 16 00010000 代表canvas
return enumStudyArr.every(item=> {
return studentNum & item;
});
}
/**
* 使用:
* 假设mike会html和svg,那么他的num就是1+8=9;
* isStudy(9, study.html, study.svg);
* 如果都会的话,1+2+4+8+16=31;
* isStudy(31, study.html, study.css, study.js, study.svg, study.canvas);
**/

let mikeNum = 9;
console.log('1->:', isStudy(mikeNum, study.html, study.svg));
console.log('2->:', isStudy(mikeNum, study.html, study.css, study.js, study.svg, study.canvas));