0

我正在尝试重构以下代码以使用 .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();
4

2 回答 2

2

你可以用filter做到这一点。迭代器使用的filter函数应该根据它是否应该包含在返回一个布尔值productsICanEat

productsICanEat = _(products).chain().filter(function(product) { 
    return !product.containsNuts && (product.ingredients.indexOf('mushrooms') === -1); 
});
于 2013-07-07T10:43:22.120 回答
1

你把事情复杂化了。

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

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

于 2013-07-07T10:43:10.537 回答