我有COLOR枚举声明如下。

export declare enum COLOR {
    RED = "RED",
    BLUE = "BLUE",
    YELLOW = "YELLOW"
}


interface IProps {
  config?: {
    disallowedColors: COLOR;
  };


现在我需要访问值config.disallowedColors。如果我想将多种颜色传递给config.disallowedColors,该怎么做?
例如我要config.disallowedColors = red, yellow

有人可以在这里阐明一下。

最佳答案

给定枚举值是字符串,则一个简单的数组就足够了,即config.disallowedColors = [COLOR.RED, COLOR.YELLOW]

检查时,您可以利用includes / some等检查是否设置了标志,例如

config.disallowedColors.includes(COLOR.RED);


当您需要检查多个值时,它会变得稍微复杂一些。一种选择是为要检查的值创建一个临时数组,然后利用every将每个值与目标数组进行比较,即

const flags = [COLOR.RED, COLOR.YELLOW];
const { disallowedColors } = config;
flags.every(c => disallowedColors.includes(c));


或者,如果使用数值,则可以利用Bitwise Operations创建一个位掩码,该掩码将为您提供相同的结果(只是以不同的方式),即

// values should be ^2
enum COLOR {
  NONE = 0
  RED = 1,
  BLUE = 2,
  YELLOW = 4,
  ...
}
...
// setting multiple flags
const colors = COLOR.RED | COLOR.YELLOW;
// check for existence of single flag
const isRed = (colors & COLOR.RED) === COLOR.RED;
// check for existence of multiple flags
const flags = COLOR.RED | COLOR.YELLOW;
const hasMultiple = (colors & flags) === flags;

10-05 22:33