简体   繁体   English

传递变量过滤回调 function

[英]Passing a variable to filter callback function

When passing a callback to filter.将回调传递给过滤器时。 value, index and Array object is passed to the callback parameters, so how is it possible for me to create a reusable filter callback where i can pass any animal type and filter accordingly.值、索引和数组 object 被传递给回调参数,所以我怎么可能创建一个可重用的过滤器回调,我可以在其中传递任何动物类型并进行相应的过滤。

I did look at How do I pass an extra parameter to the callback function in Javascript.filter() method?我确实看过How do I pass an extra parameter to the callback function in Javascript.filter() 方法? but could not get it to work as intended但无法让它按预期工作

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

This is what i want to do, I know it is not possible, but how could i achive something "similar"?这就是我想要做的,我知道这是不可能的,但我怎么能获得“相似”的东西?

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

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

do i really have to do like this?我真的必须这样做吗? or is there a way to pass a variable?或者有没有办法传递一个变量?


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

As felix-kling comment said and his already answer , you could do:正如felix-kling评论所说和他已经回答的那样,你可以这样做:

 let animals = [ { name: "fiddo", type: "dog" }, { name: "garfield", type: "cat" }, { name: "diddi", type: "bird" }, { name: "bob", type: "cat" }, ]; function filterAnyAnimal(typeVariable, animalType) { if (animalType === typeVariable) { return true; } return false; } let wordToFilter = 'cat'; console.log(animals.filter(function(element){ return filterAnyAnimal(element.type, wordToFilter); }));

 let animals = [ { name: "fiddo", type: "dog" }, { name: "garfield", type: "cat" }, { name: "diddi", type: "bird" }, { name: "bob", type: "cat" }, ]; const result = animals.map(animal=>animal.type==="dog"?true:false); console.log(result);

Map function can give you the desired result Map function可以给你想要的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM