我使用_()。any()我做错了什么?

时间:2013-07-07 10:27:48

标签: javascript underscore.js

我尝试重构以下代码以使用.filter()和.any()。我哪里错了?

目标是归还所有不含坚果或蘑菇的比萨饼。在这两种情况下,productsICanEat.length都应该=== 1.

原始代码:

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 }
];

var i,j,hasMushrooms, productsICanEat = [];

for (i = 0; i < products.length; i+=1) {
    if (products[i].containsNuts === false) {
        hasMushrooms = false;
        for (j = 0; j < products[i].ingredients.length; j+=1) {
           if (products[i].ingredients[j] === "mushrooms") {
              hasMushrooms = true;
           }
        }
        if (!hasMushrooms) productsICanEat.push(products[i]);
    }
}

重构代码:

var productsICanEat = [];

  /* solve using filter() & all() / any() */
  productsICanEat = _(products).chain()
              .filter(function(product) { 
                if(product.containsNuts === false) 
                  return product; 
                })
              .any(function(product) {

                if(product.ingredients.indexOf('mushrooms') === -1)
                  return true;
                else
                  return false;

              }).value();

2 个答案:

答案 0 :(得分:2)

您可以使用filter执行此操作。 filter迭代器使用的函数应根据它是否应包含在productsICanEat中返回一个布尔值:

productsICanEat = _(products).chain().filter(function(product) { 
    return !product.containsNuts && (product.ingredients.indexOf('mushrooms') === -1); 
});

答案 1 :(得分:1)

你过度复杂了。

var productsICanEat = _(products).filter(function(product) {
    return !product.containsNuts && product.ingredients.indexOf("mushrooms") === -1;
});

http://jsfiddle.net/Dogbert/Ap9LR/