gpt4 book ai didi

javascript - 存储有关对象的额外数据

转载 作者:行者123 更新时间:2023-11-28 07:33:29 24 4
gpt4 key购买 nike

我想存储有关对象(在本例中为配方)的一些额外数据,而不将其存储在对象本身中。最好的方法是什么?

这是一个简单的例子。我在架构上做错了什么吗?

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)与正确的食谱联系起来,而我知道这样做的唯一方法是使用相同的 key 。但这似乎很糟糕,特别是因为我必须迭代配方才能找到 key 的名称。

最佳答案

你需要传递整个食谱吗?你能不能直接把 key 传进去?

function makeRecipe(key){
var recipe = recipes[key];
if (recipe != null && recipesCooked[key] != null)) {
recipesCooked[key]++
//...snipped...make the recipe
}
}

关于javascript - 存储有关对象的额外数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28854341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com