我有一个枚举:
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}
,但我无法使成分列表以枚举值作为键
您可以将键包装在 []
中以在将它们用作键之前评估它们的值
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]);