如何使用 ES6 Fat Arrow 来 .filter() 对象数组 [英] How to use ES6 Fat Arrow to .filter() an array of objects
问题描述
我正在尝试使用带有 .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 示例:
My working ES5 example:
let adults2 = family.filter(function (person) {
if (person.age > 18) { return person; }
});
推荐答案
看来我不能使用 if 语句.
It appears I cannot use an if statement.
箭头函数允许使用表达式 或块作为它们的主体.传递表达式
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
不是表达式,if
是语句.因此,如果您想在箭头函数中使用 if
,则必须使用块:
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
的回调应该返回一个Boolean,即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.
所以你只需要
family.filter(person => person.age > 18);
在 ES5 中:
family.filter(function (person) {
return person.age > 18;
});
这篇关于如何使用 ES6 Fat Arrow 来 .filter() 对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!