Rod*_*igo 6 javascript arrays bind filter
我正在使用filter()数组助手遍历数组中的某些对象.我的想法是使用bind()创建一个动态过滤函数来遍历数组中的对象,但bind中的参数正以我所期望的不同方式使用.这是代码:
var products = [
{name:"lettuce", type:"vegetable"},
{name:"apple", type:"fruit"},
{name:"carrot", type:"vegetable"},
{name:"orange", type:"fruit"}
];
// this is the function used in filter()
function filterProducts(cat, product){
return product.type === cat;
}
// new array
var vegetables = products.filter(filterProducts.bind(products, "vegetable"));
Run Code Online (Sandbox Code Playgroud)
我假设过滤器帮助器在bind方法中的参数之后传递数组中的每个对象,所以首先是this在回调中考虑的产品,然后是我想要检查每个对象的类型,最后是对象本身.
问题是:你会建议这样做吗?我的意思是,这可以被视为一种好的做法,还是创建一个过滤每种类型而不是像这样做的函数会更好?
请考虑使用工厂功能:
var products = [
{name:"lettuce", type:"vegetable"},
{name:"apple", type:"fruit"},
{name:"carrot", type:"vegetable"},
{name:"orange", type:"fruit"}
];
function filterProducts(category) {
// this is the function used in filter()
return function filter(product) {
return product.type === category;
};
}
// new array
var vegetables = products.filter(filterProducts("vegetable"));
console.log(vegetables);Run Code Online (Sandbox Code Playgroud)
我建议使用这种模式bind,因为它更容易遵循,至少在我看来.
如果你打算filterProducts单独作为工厂使用Array#filter(),那么恭喜你,你已经读完了这个答案.如果你抱怨以下是"icky":
// product to be validated
var product = {name:"lettuce", type:"vegetable"};
// validate that product is a vegetable
if (filterProduct('vegetable')(product)) {
// code
}
Run Code Online (Sandbox Code Playgroud)
然后继续阅读.
工厂函数适用于定义一个由一个或两个关键变量不同的函数.在这种情况下,关键变量是category.如果你想要在一行代码中看起来不错的一次性功能,除非你是一个lodash狂热爱好者或者某种东西,否则你会很难找到一个......但对于这种情况,请考虑这个而不是上面的"icky"代码块:
// product to be validated
var product = {name:"lettuce", type:"vegetable"};
// vegetable validator
var isVegetable = filterProduct('vegetable');
// validate that product is a vegetable
if (isVegetable(product)) {
// code
}
Run Code Online (Sandbox Code Playgroud)
当然,bind在某些情况下可能会很好,我绝对不会建议你不惜一切代价避免它,但你应该首先问问自己,在使用之前是否真的有必要或干净利用它.
| 归档时间: |
|
| 查看次数: |
2793 次 |
| 最近记录: |