gpt4 book ai didi

Javascript 数组 filter() 与 bind()

转载 作者:数据小太阳 更新时间:2023-10-29 05:11:53 26 4
gpt4 key购买 nike

我正在使用 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"));

我假设过滤器助手在绑定(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);

我会推荐这种模式而不是使用 bind,因为它更容易遵循,至少在我看来是这样。

澄清

如果您打算将 filterProducts 仅用作 Array#filter() 的工厂,那么恭喜您,您已经阅读完此答案。如果您提示以下内容“恶心”:

// product to be validated
var product = {name:"lettuce", type:"vegetable"};

// validate that product is a vegetable
if (filterProduct('vegetable')(product)) {
// code
}

然后继续阅读。


工厂函数适用于定义一类函数,这些函数的区别在于一个或两个关键变量。在这种情况下,关键变量是 category。如果你想要一个在一行代码中看起来不错的一次性函数,你将很难找到一个,除非你是 lodash 爱好者或其他......但是对于在这种情况下,考虑这个而不是上面的“恶心”代码块:

// 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
}

当然,bind 在某些情况下可能很好,我绝对不是建议您不惜一切代价避免它,但您应该先问问自己是否真的有必要或干净地使用它求助于它。

关于Javascript 数组 filter() 与 bind(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38664706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com