出色的JavaScript书:不了解示例

问题描述

在第3章中,有一个Hummus食谱示例,我真正不理解的是这样的代码

const hummus = function(factor) {
  const ingredient = function(amount,unit,name) {
    let ingredientAmount = amount * factor;
    if (ingredientAmount > 1) {
      unit += "s";
    }
    console.log(`${ingredientAmount} ${unit} ${name}`);
  };
  ingredient(1,"can","chickpeas");
  ingredient(0.25,"cup","tahini");
  ingredient(0.25,"lemon juice");
  ingredient(1,"clove","garlic");
  ingredient(2,"tablespoon","olive oil");
  ingredient(0.5,"teaspoon","cumin");
};

添加了两个console.log,以试图更好地跟踪进度并了解实际发生的事情,但是我无法解决这个问题。我的意思是这里的预期结果是什么?

解决方法

该示例的目的是向您展示函数范围。通过将固定参数传递给hummus函数,您可以返回一些新的文字对象,该对象将通过使用内部函数和外部函数参数因子来计算最终结果。

,

只需添加鹰嘴豆泥(数量)即可获得成分的输出

鹰嘴豆泥(5);在代码末尾调用函数

输出: 5罐鹰嘴豆 1.25 杯芝麻酱 1.25 杯柠檬汁 5瓣大蒜 10汤匙橄榄油 2.5 茶匙孜然