首页 > 解决方案 > nodejs中最接近枚举的实现是什么?

问题描述

许多语言都有枚举作为内置类型。

我需要知道使用以下语法在节点中最接近的枚举实现是什么:

enum Types{
  TypeA,
  TypeB,
  TypeC,
}

我想像这样使用它。(我不想为每个变量赋值)

let x = Types.TypeA;

if(x == Types.TypeA){
   console.log('A')
}
if(x == Types.TypeB){
   console.log('B')
}

标签: node.jsenums

解决方案


您实际上可以将 Typescript 用于枚举 - 如果您想要提高性能,可以加分:使用 const enum :)

来自https://www.typescriptlang.org/docs/handbook/enums.html

常量枚举只能使用常量枚举表达式,并且与常规枚举不同,它们在编译期间会被完全删除。常量枚举成员在使用站点内联。这是可能的,因为 const 枚举不能有计算成员。

const enum Direction {
  Up,
  Down,
  Left,
  Right,
}
 
let directions = [
  Direction.Up,
  Direction.Down,
  Direction.Left,
  Direction.Right,
];

in generated code will become

"use strict";
let directions = [
    0 /* Up */,
    1 /* Down */,
    2 /* Left */,
    3 /* Right */,
];

如果您不想使用 Typescript(尽管我强烈推荐它),恐怕您将不得不求助于一个对象:

const Types = {
  "TypeA": 0,
  "TypeB": 1,
  "TypeC": 2,
}

推荐阅读