用惯用的javascript写一个过滤器

时间:2015-12-30 20:57:32

标签: javascript

我有这个过滤器,我不喜欢这样:

var products = this.store.filter('product', function(product) {
    var ok = true;
    if (compatibility) {
        ok = ok && product.compatibility == compatibility;
    }
    if (format) {
        ok = ok && product.format == format;
    }
    if (priceRange) {
        ok = ok && product.priceRange == priceRange;
    }
    if (productType) {
        ok = ok && product.productType == productType;
    }
    return ok;
});

基本上,对于通过测试的产品,过滤函数必须返回true,对于未通过测试的产品,过滤函数必须返回false。过滤器参数的值可以为null

重写过滤函数的惯用方法是什么?

1 个答案:

答案 0 :(得分:2)

对于每个失败的测试,立即return false;。如果您知道它失败了,那么进一步处理是没有意义的。

if( compatibility && product.compatibility != compatibility) {
    return false;
}
// ...
return true;

或者,(提示:不要这样做!),你可以做一个很长的单行:

return (!compatibility || product.compatibility == compatibility) && (!format || product.format == format) // ...
// interestingly this shortcuts just like the "immediately return false" solution