问题描述
我试图用 .filter 使用ES6箭头功能来返回成年人(Jack& Jill)。看来我不能使用if语句。
I'm trying to use ES6 arrow function with .filter to return adults (Jack & Jill). It appears I cannot use an if statement.
为了在ES6中做到这一点,我需要知道什么?
What do I need to know in order to do this in ES6?
var family = [{"name":"Jack", "age": 26}, {"name":"Jill", "age": 22}, {"name":"James", "age": 5 }, {"name":"Jenny", "age": 2 }]; let adults = family.filter(person => if (person.age > 18) person); // throws error (8:37) SyntaxError: unknown: Unexpected token (8:37) |let adults = family.filter(person => if (person.age > 18) person);
我工作的ES5示例:
let adults2 = family.filter(function (person) { if (person.age > 18) { return person; } });
推荐答案
箭头函数允许使用表达式 或 块作为其主体。传递表达式
Arrow functions either allow to use an expression or a block as their body. Passing an expression
foo => bar
相当于以下块
foo => { return bar; }
但是,
if (person.age > 18) person
不是表达式, 如果是一个语句。因此,如果您想在箭头函数中使用 ,则必须使用块:
is not an expression, if is a statement. Hence you would have to use a block, if you wanted to use if in an arrow function:
foo => { if (person.age > 18) return person; }
虽然技术上解决了这个问题,混淆使用 .filter ,因为它建议您必须返回应包含在输出数组中的值。但是,传递给 .filter 的回调应该返回一个布尔值,即 true 或 false ,表示元素是否应该包含在新数组中。
While that technically solves the problem, this a confusing use of .filter, because it suggests that you have to return the value that should be contained in the output array. However, the callback passed to .filter should return a Boolean, i.e. true or false, indicating whether the element should be included in the new array or not.
所以你需要的只是
So all you need is
family.filter(person => person.age > 18);
在ES5中:
family.filter(function (person) { return person.age > 18; });
这篇关于如何使用ES6 Fat Arrow来.filter()一个对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!