用惯用的javascript编写一个过滤器
Write a filter in idiomatic 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;
});
基本上,filter函数必须为通过测试的产品返回true
,为未通过测试的返回false
。滤波器参数的值可以是null
。
重写过滤函数的惯用方法是什么?
对于每一个失败的测试,立即使用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
相关文章:
- 为复选框列表 - 动态响应列表创建一个过滤器搜索框
- Angular JS - 创建一个过滤器来比较 2 个数组
- 用惯用的javascript编写一个过滤器
- 当添加一个服务和一个过滤器或多个服务时,我在做什么导致未知提供者
- 在VueJS中,从Vue实例内的方法调用一个过滤器
- 如何将Spine.js与数百万条记录和一个过滤器一起使用
- 在AngularJS中用表单传递一个过滤器
- 链接collection_select菜单选项到一个过滤器方法——Ruby on Rails
- 结合& # 39;orderBy& # 39;用Angular中的另一个过滤器
- Rails 4 / JS / HTML无法添加下拉菜单,所以它为HTML表创建了一个过滤器
- 如何创建一个过滤器,在列出其他对象之前显示一个对象?
- ReactJs试图创建一个过滤器列表
- 在AngularJS中对动态表的每一列应用一个过滤器
- 我如何通过ajax加载数据库内容之前,一个过滤器键被按下
- 我在Angularjs中有一个过滤器,它返回"TypeError: Cannot read property
- 在AngularJS中还原一个过滤器
- 如何在一个剑道组合框完成一个过滤器后触发一个事件
- 使用select和jQuery在表上创建一个过滤器
- Ramda.js通过对象值创建一个过滤器函数
- 使用纯JavaScript,给定一个对象集合和一个过滤器对象,返回集合中与过滤器对象具有相同键/值对的对象