欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

js 枚举的简单使用示例

最编程 2024-04-22 10:39:03
...

 枚举可以解决多if esle 语句分支,代码更有可读性。直接上代码:

// 枚举

// 使用Object.keys()方法来获取对象的可枚举属性的数组
const Enum = Object.create(null);
 
// 定义枚举属性,Object.defineProperties()创建不可枚举枚举的枚举属性
Object.defineProperties(Enum, {
  "FIRST": {
    value: 0,
    enumerable: false
  },
  "SECOND": {
    value: 1,
    enumerable: false
  },
  "THIRD": {
    value: 2,
    enumerable: false
  }
});
 
// 使用枚举
console.log(Enum.FIRST); // 0
console.log(Enum.SECOND); // 1
console.log(Enum.THIRD); // 2
 
// 枚举对象的键,枚举属性不是对象的可枚举属性
console.log(Object.keys(Enum)); // 输出: []

console.log("---------------简单枚举-------------------")
// 简单的对象策略模式枚举
const obj = {
    "FIRST": 0,
    "SECOND": 1,
    "THIRD": 2
}
// 使用枚举
console.log(obj.FIRST); // 0

// 简单的策略模式
const day = 'tuesday';
const days = {
    'monday': 0,
    'tuesday': 1,
    'wednesday': 2,
    'thursday': 3,
    'friday': 4,
}
// 使用枚举,如果找不到则返回-1
const index = days[day]??-1;
console.log(index)

console.log("---------------性别枚举-------------------")
// 性别枚举
const gender = 2;
const genders = {
    0: "未知",
    1: "男",
    2: "女"
}
// 使用枚举,如果找不到则返回-1
const genderIndex = genders[gender]??-1;
console.log(genderIndex)

推荐阅读