[英]How to create multiple booleans in a javascript function/loop?
我有这段代码:
function restrictListProducts(prods, restriction) {
let product_names = [];
for (let i=0; i<prods.length; i+=1) {
if ((restriction == "Vegetarian") && (prods[i].vegetarian == true)) {
product_names.push(prods[i].name);
}
else if ((restriction == "GlutenFree") && (prods[i].glutenFree == true)){
product_names.push(prods[i].name);
}
else if (restriction == "None"){
product_names.push(prods[i].name);
}
}
return product_names;
}
用户输入他们的饮食限制并显示可用食物列表。 还询问用户是否希望他们的食物是有机的。 我应该如何修改这个 function 以便考虑到有机食品,因为所有当前类别(素食、GF 等)都可以是有机和非有机的。
产品是这样组织的:
var products = [
{
name: "brocoli",
vegetarian: true,
glutenFree: true,
organic: true,
price: 1.99
},
为什么不将限制用作具有相同命名字符串的数组,就像它们对应的产品键一样。
因为Array#every
为空的 arrays 返回true
,所以没有任何内容。
selection = products.filter(product => restrictions.every(k => product[k]));
const products = [{ name: "broccoli", vegetarian: true, glutenFree: true, organic: true, price: 1.99 }, { name: "matso", vegetarian: true, glutenFree: true, organic: false, price: 1.99 } ] const getSelection = (products, restrictions) => { return products.filter(product => restrictions.every(k => product[k])); }; console.log(getSelection(products,["vegetarian","organic"])) console.log(getSelection(products,["vegetarian","glutenFree"]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.