JS数组的Reduce方法

Array的reduce

  • reduce() 方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其简化为单个值。

  • reduce为数组中的每一个元素依次执行callback函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:

accumulator 累加器
currentValue 当前值
currentIndex 当前索引
array 数组

  • 回调函数第一次执行时,accumulator 和currentValue的取值有两种情况:如果调用reduce()时提供了initialValue,accumulator取值为initialValue,currentValue取数组中的第一个值;如果没有提供 initialValue,那么accumulator取数组中的第一个值,currentValue取数组中的第二个值。

    // 求和
   var total = [0, 1, 2, 3].reduce(
        (acc, cur) => acc + cur,
        0
    );
    // sum is 6


   // 将二维数组转化为一维
 var arr = [
       [0, 1],
       [2, 3],
       [4, 5]
   ].reduce(
       (acc, cur) => acc.concat(cur),
        []
   );
   // arr is [0, 1, 2, 3, 4, 5]


// 计算数组中每个元素出现的次数
  var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
  var count = names.reduce(function(allNames, name) {
      if (name in allNames) {
          allNames[name]++;
      } else {
          allNames[name] = 1;
      }
      return allNames;
  }, {});
  console.log(count);

  // count is:
  // { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }


// 数组去重
 let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
 let result = arr.sort().reduce((init, current) => {
     if (init.length === 0 || init[init.length - 1] !== current) {
         init.push(current);
     }
     return init;
 }, []);

 //[1,2,3,4,5]


 //对象取值

let getValue = (source, target) => {
     let reg = /{{([^}]+)}}/g;
     return reg.exec(target)[1].split('.').reduce((pre, next) => {
         return pre[next];
     }, source);
 };

 let test = {
     author: 'Somebody',
     title: 'Title of article',
     category: {
         ngCached: true,
         ngxCachedTime: 1536311340,
         title: 'frontend'
     },
     user: {
         isAuthor: false,
         role: 'guest',
         community: {
             uid: 19499773,
             updateAt: '2018-09-05T02:27:13.630Z'
         }
     }
 };

 let uid = '{{ user.community.uid }}';

 let date = getValue(test, uid);

 console.log(uid); // 19499773

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值