.map() .filter() .reduce()区别及用法

.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);

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值