Javascript:Concat布尔函数

use*_*412 3 javascript boolean concat filter

我想写一个过滤多个标准数据的方法.这些标准应作为函数传递给filter-function,例如:

var products = [/* some data */];
function filterMyProducts(criteria) {
   return products.filter(/* I'm asking for this code */);
}

function cheap(product) {
    return product.price < 100;
}

function red(product) {
    return product.color == "red";
}

// find products that are cheap and red
var result = filterMyProducts([cheap, red]);
Run Code Online (Sandbox Code Playgroud)

如何将数组中传递的条件与过滤器函数结合起来?我希望它们与布尔AND结合使用.

the*_*eye 7

function validateProduct(listOfFunctions) {
    return function(currentProduct) {
        return listOfFunctions.every(function(currentFunction) {
            return currentFunction(currentProduct);
        });
    }
}

function filterMyProducts(criteria) {
    return products.filter(validateProduct(criteria));
}
Run Code Online (Sandbox Code Playgroud)

Working Demo

  • @ user2033412而不是`listOfFunctions.every`你必须使用`listOfFunctions.some`来获得布尔的`OR`行为:) (3认同)