我正在使用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"));
我假设filter助手会在绑定方法中将每个对象逐个传递,因此首先是产品,这代表回调函数中的
this
,然后是我想要检查每个对象的类型,最后是对象本身。问题是:您是否建议这样做?我的意思是,这种方式可否被视为良好的实践,还是最好创建一个函数来过滤每种类型而不是像这样做?