.map()
对数组的每个元素都遍历一次,同时返回一个新的值。记住一点是返回的这个数据的长度和原始数组长度是一致的。
例:收到一组包含多个对象的数组,每个对象是一个 person。最终你只希望得到一个只包含 id 的数组。
var officers = [
{ id: 20, name: 'Captain Piett' },
{ id: 24, name: 'General Veers' },
{ id: 56, name: 'Admiral Ozzel' },
{ id: 88, name: 'Commander Jerjerrod' }
];
var officersIds = officers.map(function (officer) {
return officer.id
});
// 箭头函数
const officersIds = officers.map(officer => officer.id);
.filter()
如果 callback 函数返回 true,这个元素将会出现在返回的数组中,如果返回 false 就不会出现在返回数组中。
例:有一个数组,你只想要这个数组中是 rebel 飞行员的元素。
var pilots = [
{id: 2, name: "Wedge Antilles", faction: "Rebels"},
{id: 8, name: "Ciena Ree", faction: "Empire"}
];
var rebels = pilots.filter(function (pilot) {
return pilot.faction === "Rebels";
});
// 箭头函数
const rebels = pilots.filter(pilot => pilot.faction === "Rebels");
.reduce()
直观的返回数组里面指定的一个值或者对象
例:有一个数组,你想要这个数组中所有飞行员的总飞行年数。
var pilots = [
{id: 10, name: "Poe Dameron", years: 14},
{id: 2, name: "Temmin 'Snap' Wexley", years: 30}
];
// 用0初始化了accumulator 的
var totalYears = pilots.reduce(function (accumulator, pilot) {
return accumulator + pilot.years;
}, 0);
// 箭头函数
const totalYears = pilots.reduce((acc, pilot) => acc + pilot.years, 0);
假如我们需要知道飞行员中飞行年限最长的那位,可以这样获取:
var mostExpPilot = pilots.reduce(function (oldest, pilot) {
return (oldest.years || 0) > pilot.years ? oldest : pilot;
}, {});
.map() .filter() .reduce() 结合使用
因为 .map() 和 .filter()都返回一个数组,所以我们可以轻松的用链式编程的方法来综合使用它们。
例:有一个数组,获取属性isForceUser为 true的用户总值
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}
];
var totalJediScore = personnel
.filter(function (person) {
return person.isForceUser;
})
.map(function (jedi) {
return jedi.pilotingScore + jedi.shootingScore;
})
.reduce(function (acc, score) {
return acc + score;
}, 0);
// 箭头函数
const totalJediScore = personnel
.filter(person => person.isForceUser)
.map(jedi => jedi.pilotingScore + jedi.shootingScore)
.reduce((acc, score) => acc + score, 0);