.map() .filter() .reduce() 的用法
.map()
让我用一些简单的例子来解释它是如何工作的。 如果说你收到一组包含多个对象的数组,每个对象是一个 person。最终你只希望得到一个只包含 id 的数组。
var officersIds = [];
officers.forEach(function (officer) {
officersIds.push(officer.id);
});
可以注意到,你不得不先创建一个空数组?让我们来看看.map()是如何做到的。
const officersIds = officers.map(officer => officer.id);
那么 .map() 是怎么运行的呢?实际上对数组的每个元素都遍历一次,同时返回一个新的值。记住一点是返回的这个数据的长度和原始数组长度是一致的。
.filter()
假如你有一个数组,你只想要这个数组中的一些元素怎么办呢?这时候 .filter() 就非常好用了。
var rebels = pilots.filter(function (pilot) {
return pilot.faction === "Rebels";
});
var empire = pilots.filter(function (pilot) {
return pilot.faction === "Empire";
});
我们还可以用箭头函数更优雅的表达:
var pilots = [
{
id: 10,
name: "Poe Dameron",
years: 14,
},
{
id: 2,
name: "Temmin 'Snap' Wexley",
years: 30,
},
{
id: 41,
name: "Tallissan Lintra",
years: 16,
},
{
id: 99,
name: "Ello Asty",
years: 22,
}
];
如果你需要知道所有飞行员的总飞行年数。用 .reduce() 将会非常直观。
const totalYears = pilots.reduce((acc, pilot) => acc + pilot.years, 0);
假如我们需要知道飞行员中飞行年限最长的那位,我们可以这样获取:
var personnel = [
{
id: 5,
name: "Luke Skywalker",
pilotingScore: 98,
shootingScore: 56,
isForceUser: true,
},
{
id: 82,
name: "Sabine Wren",
pilotingScore: 73,
shootingScore: 99,
isForceUser: false,
},
{
id: 22,
name: "Zeb Orellios",
pilotingScore: 20,
shootingScore: 59,
isForceUser: false,
},
{
id: 15,
name: "Ezra Bridger",
pilotingScore: 43,
shootingScore: 67,
isForceUser: true,
},
{
id: 11,
name: "Caleb Dume",
pilotingScore: 71,
shootingScore: 85,
isForceUser: true,
},
];
我们的目标是:获取属性为 force 的用户总值,读者可以先自行思考一下,用于巩固前面所学知识,我们可以如下处理。
const totalJediScore = personnel
.filter(person => person.isForceUser)
.map(jedi => jedi.pilotingScore + jedi.shootingScore)
.reduce((acc, score) => acc + score, 0);
链接:https://www.jianshu.com/p/e87b195f6943