我想存储一些关于对象的额外数据(在本例中为配方),而不将其存储在对象本身中。这样做的最佳方式是什么?
这是一个简单的例子。我在建筑上做错了吗?
var recipes = {
scones: {egg:2, milk: 5},
pancakes: {eggs:3, milk: 2}
}
var recipesCooked = {
scones: 0,
pancakes: 0
}
function makeRecipe(recipe){
// I don't want to have to do this loop every time.
// Is there a better way of storing this data??
for(var key in recipes) {
if(recipes.hasOwnProperty(key) && recipes[key] === recipe){
recipesCooked[key]++;
}
}
//...snipped...make the recipe
}
makeRecipe(recipes.pancakes);
//recipesCooked.pancakes should be 1
换句话说:我需要一些方法将额外数据(recipesCooked)绑定到正确的配方,而我知道这样做的唯一方法是使用相同的密钥。但这看起来很糟糕,特别是因为我必须重复修改食谱以找到密钥的名称。
答案 0 :(得分:0)
你需要传递整个食谱吗?你能不能把密钥传递进去?
function makeRecipe(key){
var recipe = recipes[key];
if (recipe != null && recipesCooked[key] != null)) {
recipesCooked[key]++
//...snipped...make the recipe
}
}
答案 1 :(得分:0)
也许您需要更改makeRecipe
的签名。没有必要成为一个循环:
var recipes = {
scones: {egg:2, milk: 5},
pancakes: {eggs:3, milk: 2}
}
// no need for properties, [makeRecipe] takes care of that
var recipesCooked = { };
// parameter recipe should be a string
function makeRecipe( recipe ){
if (!recipes[recipe]) { throw 'recipe ' + reicpe + ' not found'; }
if (recipe in reicpesCooked) { recipesCooked[recipe] += 1; }
else { recipesCoocked[reciped] = 1; }
// and start cooking
}
makeRecipe('scones');