【问题标题】:How do I find same keys in objects and calculate the values如何在对象中找到相同的键并计算值
【发布时间】:2020-03-11 11:24:28
【问题描述】:

我如何检查来自pizzaRecipe 的键是否在walmart 对象中并计算值,以便我可以得到在walmart 中购买pizzaRecipe 成分的价格。

var walmart = {
    cheese: 9,
    corn: 2,
    wine: 7,
    parsley: 1,
    coconut: 3,
    tomato: 4,
    potato: 6,
    tomato: 2
};

var pizzaRecipe = {
    cheese: 2,
    tomato: 4,
    parsley: 1
};

function costRecipeInStore(recipe, store) {};

【问题讨论】:

标签: javascript function object


【解决方案1】:

您可以尝试以下方法:

function costRecipeInStore(recipe, store) {
     let cost = 0;
     for (let obj in recipe) {
         if (store.hasOwnProperty(obj)) {
             cost += recipe[obj] * store[obj]
         }
     }
     console.log(cost)
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2022-11-03
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多