【问题标题】:Using Enum as Object keys [duplicate]使用枚举作为对象键[重复]
【发布时间】:2019-02-17 03:36:24
【问题描述】:

我有一个枚举:

   const ingredients = {
      BREAD_BOTTOM: 'BreadBottom',
      BREAD_TOP: 'BreadTop',
      MEAT: 'Meat',
      BACON: 'Bacon',
      CHEESE: 'Cheese',
      SALAD: 'Salad'
   };

现在我想使用这个枚举创建一个成分列表,例如:

    listOfIngredients: {
      ingredients.BREAD_TOP: 1,
      ingredients.BACON: 1,
      ingredients.CHEESE: 2,
      ingredients.MEAT: 2,
      ingredients.BREAD_BOTTOM: 1,
    }

我尝试了一些变体,例如${ingredients.BREAD_TOP},但我无法让成分列表以枚举值作为关键

【问题讨论】:

  • 嗯,它真的不是一个“枚举”;它是一个具有字符串值属性的对象。但是,您可以使用 [ ] 来提取第二个对象字面量中的属性值。
  • 您希望密钥是什么?枚举的值?

标签: javascript


【解决方案1】:

您可以将密钥包装在[] 中以在将它们用作密钥之前评估它们的值

const listOfIngredients: {
      [ingredients.BREAD_TOP]: 1,
      [ingredients.BACON]: 1,
      [ingredients.CHEESE]: 2,
      [ingredients.MEAT]: 2,
      [ingredients.BREAD_BOTTOM]: 1,
}

要访问一个值,只需:

console.log(listOfIngredients[ingredients.BREAD_TOP]);

这是一个sn-p:

let ingredients = {
  BREAD_BOTTOM: 'BreadBottom',
  BREAD_TOP: 'BreadTop',
  MEAT: 'Meat',
  BACON: 'Bacon',
  CHEESE: 'Cheese',
  SALAD: 'Salad'
};

const listOfIngredients= {
      [ingredients.BREAD_TOP]: 1,
      [ingredients.BACON]: 1,
      [ingredients.CHEESE]: 2,
      [ingredients.MEAT]: 2,
      [ingredients.BREAD_BOTTOM]: 1
};

console.log(listOfIngredients[ingredients.BREAD_TOP]);

【讨论】:

    猜你喜欢
    • 2018-10-30
    • 2022-09-23
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 2018-05-07
    • 2019-06-29
    • 1970-01-01
    相关资源
    最近更新 更多