gpt4 book ai didi

javascript - 有没有办法通过 .filter() 传递额外的参数?

转载 作者:行者123 更新时间:2023-11-28 17:42:58 25 4
gpt4 key购买 nike

在下面的简化示例中,生物数组被过滤以查找具有僵尸物种的所有对象。按照目前的情况,回调函数 filterCreatures 只能搜索单词 Zombie。不过,我想传递一个具有不同生物名称的变量,以便我可以重用该函数来搜索每种类型的怪物。例如,它看起来像,return a.species === BrevetType; 我该怎么做?有没有办法用 .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);

最佳答案

你可以创建这样的东西。创建一个采用 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);

关于javascript - 有没有办法通过 .filter() 传递额外的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47482973/

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