通过迭代数组中的元素来初始化属性来创建计数对象

Making a count object by initializing properties from iterating through elements in an array

好的,我正在研究 javascript-koans 的最后一个问题。我给出的代码和数据集如下:

products = [
   { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
   { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
   { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
   { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
   { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
];

it("should count the ingredient occurrence (imperative)", function () {
  var ingredientCount = { "{ingredient name}": 0 };
    for (i = 0; i < products.length; i+=1) {
      for (j = 0; j < products[i].ingredients.length; j+=1) {
        ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1;
      }
    }
  expect(ingredientCount['mushrooms']).toBe();
});

我想我理解了一些正在发生的事情:我们正在遍历产品数组以遍历每个产品的成分数组,获取一种成分,并使用括号表示法将其称为 属性 来自 ingredientCount 对象。但在这里我失去了它,因为我们将它设置为等于它本身或零,然后不管怎样都加一。有人可以纠正我那里的错误并解释我所缺少的吗? How/where 在括号中用 'mushrooms' 调用 ingredientCount 变量是否在这个表达式中建立 'mushrooms'?我们如何在不显式引用的情况下增加 ingredientCount 的 {ingredient name} 属性?是否存在某种隐式赋值或正在发生的事情?

此外,测试运行程序 returns 一个错误让我知道预期结果应该是 2。

我明白了。我对该代码的书面总结是正确的,除了我们在这段代码中看到的不仅仅是一个表达式,更重要的是它是一个变量赋值。因此,在对每种产品的每种成分进行每次迭代时,我们都会在 ingredientCount 对象中初始化一个新的 属性 并将其设置为等于自身或零。但为什么要这样做?因为如果你将一个不存在的对象的 属性 设置为等于它自己,你就会得到未定义的——它不会初始化。幸运的是,undefined 是一个 falsey value,因此如果 属性 不存在,它会通过设置为零进行初始化,然后递增为 1。之后,每个现有成分的每个额外计数都采用真实数值(跳过或后的零)并加一。因此,当我们从控制台查看结果时,我们看到 ingredientCount 对象的行为并不像一个函数(正如我之前认为的那样感到困惑),相反,它是一个简单的对象,具有我们可以访问的属性,可以为我们提供它们的属性个人计数:

[object Object] {
  artichoke: 1,
  black beans: 1,
  blue cheese: 1,
  garlic: 1,
  goats cheese: 1,
  jalapenos: 1,
  kalamata olives: 1,
  mushrooms: 2,
  roma: 1,
  rosemary: 1,
  sesame seeds: 1,
  spinach: 1,
  sundried tomatoes: 2,
  walnuts: 1
  {ingredient name}: 0
}

{ingredient name} 只是在代码中作为占位符,这就是它显示在底部的原因。