7

我有一个枚举:

   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}但我不能让成分列表作为 Enum 值的关键

4

1 回答 1

18

在将它们用作键之前,您可以将键包装起来[]以评估它们的值

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]);

这是一个片段:

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-09-12T13:16:25.087 回答