在下面的简化示例中,对物种Zombie的所有objects
过滤生物数组。目前,回调函数filterCreatures
只能搜索Zombie这个词。但是,我想传递一个具有不同生物名称的变量,以便我可以重复使用该函数来搜索每种类型的怪物。例如,它看起来像return a.species === creatureType;
我该怎么做?有没有办法用.filter()
传递额外的变量?非常感谢!
'use strict';
var creatures = [], zombieCreatures = [];
var filterCreatures;
creatures = [
{species: 'Zombie', hitPoints: 90},
{species: 'Orc', hitPoints: 40},
{species: 'Skeleton', hitPoints: 15},
{species: 'Zombie', hitPoints: 85}
];
filterCreatures = function(a) {
return a.species === 'Zombie';
}
zombieCreatures = creatures.filter(filterCreatures);
console.log(zombieCreatures);
答案 0 :(得分:2)
你可以创建这样的东西。创建一个取filter
属性并返回实际过滤函数的函数。
'use strict';
var creatures = [], zombieCreatures = [];
var filterFactory;
creatures = [
{species: 'Zombie', hitPoints: 90},
{species: 'Orc', hitPoints: 40},
{species: 'Skeleton', hitPoints: 15},
{species: 'Zombie', hitPoints: 85}
];
filterFactory = function(filter) {
return function(a) {
return a.species === filter;
};
};
zombieCreatures = creatures.filter(filterFactory('Zombie'));
console.log(zombieCreatures);
zombieCreatures = creatures.filter(filterFactory('Orc'));
console.log(zombieCreatures);

答案 1 :(得分:1)
您可以使用bind
这样的功能
filterCreatures = function(creatureType, a) {
return a.species === creatureType;
}
zombieCreatures = creatures.filter(filterCreatures.bind(null, 'Zombie'));
答案 2 :(得分:0)
可以通过稍微修改代码来完成。
创建一个接受任何数组的函数和一个要过滤的元素
var creatures = [],
zombieCreatures = [];
var filterCreatures;
creatures = [{
species: 'Zombie',
hitPoints: 90
},
{
species: 'Orc',
hitPoints: 40
},
{
species: 'Skeleton',
hitPoints: 15
},
{
species: 'Zombie',
hitPoints: 85
}
];
function filterCreatures(array, crt) {
return array.filter(function(a) {
return a.species === crt;
})
}
console.log(filterCreatures(creatures, 'Skeleton'));