TS 枚举枚举用法
最编程
2024-04-22 10:29:44
...
1.概述
枚举用于定义数据集合,使用枚举可以定义一些带名字的常量,有普通枚举、字符串枚举和常量枚举等类型。
2.示例
- 普通枚举:初始值默认为 0,其余的属性按顺序依次递增。
enum Color {
Red,
Blue,
Green
}
console.log(Color.Red); //0
// const red:Color=Color.Red;
// console.log(red);
也可手动设置初始值(其余的属性依旧按顺序递增):
enum Color {
Red=3,
Blue,
Green
}
console.log(Color.Red); //3
- 字符串枚举:
enum Color {
Red='红色',
Blue='蓝色',
Green='绿色'
}
console.log(Color.Blue); //蓝色
- 常量枚举:使用 const 关键字修饰的枚举
const enum Color {
Red,
Blue,
Green
}
console.log(Color.Red,Color.Blue,Color.Green); //0 1 2
3.枚举的实际应用
//enum.ts
/** 登录状态 */
export enum LoginStatus { //普通枚举
Login,
Register,
}
//LoginStatus[0]---'Login'
//index.vue
<template>
<el-button color="#4A52FF" class="w-284px h-54px rounded-6px text-20px font-light" type="primary"
@click="userLogin">
登录
</el-button>
</template>
<script setup lang='ts'>
import { LoginStatus } from '~/types';
</script>
可修改为:
//enum.ts
/** 登录状态 */
export enum LoginStatus { //中文的字符串枚举
'登录',
'注册',
}
//LoginStatus['登录']---0
//LoginStatus[0]---登录
//index.vue
<template>
<el-button color="#4A52FF" class="w-284px h-54px rounded-6px text-20px font-light" type="primary"
@click="userLogin">
{{ LoginStatus[0] }} //登录
</el-button>
</template>
<script setup lang='ts'>
import { LoginStatus } from '~/types';
</script>
英文的普通枚举
只有一种作用:只能通过数组下标读出枚举里的属性,不便于代码的理解。
LoginStatus[0]---'Login'
中文的字符串枚举
有两种作用:
1.当用中文形式时,可以显示出对象属性的索引。LoginStatus['登录']---0
2.当用数组下标形式时,可以显示出中文,以便提高代码的可读性与理解。LoginStatus[0]---登录
所以,项目中建议使用中文的字符串枚举。
上一篇: Java 枚举的定义和用法
下一篇: Swift 编程枚举类型详解
推荐阅读
-
C++STL 开发复习与总结(六): 6. C++ 语言输入/输出流 输入/输出格式的定义 控制-2-1 枚举常量(在 ios 类中)
-
Python 使用枚举计算游戏 "24 点" - 分布简介
-
Python 计算二十一点游戏的枚举算法
-
用 VC MFC 实现串行端口号枚举,并支持串行端口热插拔功能
-
QWidget | Qt::WindowType 枚举 & QFlags 模板类说明
-
Kotlin 语法入门 - 数据类、辅助类、枚举类 (9)
-
Python 中的 "枚举 "函数有什么作用?
-
Java 枚举类型枚举的使用技巧和效率收益
-
在 Laravel 中使用枚举
-
如何使用枚举值?总结枚举值的使用示例