我试图将参数名称从getAnimalByName函数传递到嵌套在其中的函数的返回值。为什么它不能正常工作?现在,如果我调用getAnimalByName,它将返回animals数组中的所有对象,而不仅仅是返回作为参数传递的对象。
var animals=[
{type: 'mammal', subType: 'dog', name: 'spot', weight: 50},
{type: 'reptile', subType: 'lizard', name: 'gicko', weight: 1},
{type: 'reptile', subtype: 'snake', name: 'buba', weight: 3},
{type: 'mammal', subType: 'rat', name: 'runner', weight: 3}
];
function getAnimalByName(name){
var animal= animals.filter(function(event){
return event.name;
});
return animal;
}
var spot= getAnimalByName('spot');
var gicko= getAnimalByName('gicko');
var buba= getAimalsByName('buba');
var runner= getAnimalByName('runner');
过滤器的工作方式在我们需要指定的函数内,即该特定数组元素是否匹配特定条件,因此,在内部,过滤器函数除了atruthy
或一个falsy
值外,由于您返回event.name
,所以它始终是一个truthy
值,并以此将值推入新数组,因此返回了整个动物数组。
所以这就是为什么你应该回来的原因
return event.name === name
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句