You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为JavaScript的filter()传递自定义参数实现可复用过滤回调

如何创建可复用的filter过滤函数来筛选任意动物类型?

在JavaScript中使用filter()方法时,回调函数只会接收元素、索引和数组对象这三个参数。我想做一个可复用的过滤回调函数,能传入任意动物类型来过滤数组。现有动物数组如下:

let animals = [
  { name: "fiddo", type: "dog" },
  { name: "garfield", type: "cat" },
  { name: "diddi", type: "bird" },
  { name: "bob", type: "cat" },
];

我原本想写类似下面的代码(但知道这么写行不通),该怎么实现类似效果?

function filterAnyAnimal(animal, index, arr, typeVariable) {
  if (animal.type === typeVariable) {
    return true;
  }
  return false;
}

console.log(animals.filter(filterAnyAnimal));

难道必须像下面这样给每种动物单独写函数吗?有没有办法传递自定义参数?

function isDog(animal) {
  if (animal.type === "dog") {
    return true;
  }
  return false;
}

不用单独写多个函数,这几种方法可以实现复用

方法1:高阶函数(最推荐)

写一个返回回调函数的外层函数,把要筛选的类型存在闭包里,这样每次调用时就能指定不同类型:

function filterByType(type) {
  return function(animal) {
    return animal.type === type;
  }
}

// 调用示例
console.log(animals.filter(filterByType("dog"))); // 输出所有狗的对象
console.log(animals.filter(filterByType("cat"))); // 输出所有猫的对象

嫌代码长?还能写成更简洁的箭头函数版本:

const filterByType = type => animal => animal.type === type;

方法2:利用filter的thisArg参数

filter方法本身支持第二个参数,用来设置回调函数里的this指向。可以把要筛选的类型放到这个参数里:

function filterAnyAnimal(animal) {
  return animal.type === this.type;
}

// 调用时把类型放到第二个参数里
console.log(animals.filter(filterAnyAnimal, { type: "bird" }));

注意:如果回调用箭头函数,this会绑定外层作用域,这种方法就失效了,所以不如高阶函数灵活。

方法3:直接写箭头函数(临时场景用)

如果只是临时筛选某一种类型,直接在filter里写箭头函数更省事:

// 直接筛选鸟类
console.log(animals.filter(animal => animal.type === "bird"));

内容的提问来源于stack exchange,提问作者Soma Juice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:05:42