【发布时间】:2016-02-03 07:04:55
【问题描述】:
好的,所以我正在处理 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();
});
我想我理解了一些正在发生的事情:我们正在遍历 products 数组以遍历每个产品的成分数组,获取一种成分,并使用括号表示法将其作为来自 ingredientsCount 对象的属性进行调用。但是这里是我丢失它的地方,因为然后我们将它设置为等于自身或零,然后不管怎样都加一。有人可以纠正我那里的错误并解释我所缺少的吗?如何/在哪里用括号表示法中的“蘑菇”调用成分计数变量在此表达式中建立“蘑菇”?我们如何在不显式引用的情况下增加成分计数的 {ingredient name} 属性?是否有某种隐式赋值或发生了什么?
另外,测试运行器返回一个错误,让我知道预期的结果应该是 2。
【问题讨论】:
标签: javascript properties jasmine variable-assignment