箭头函数和数组

2019-10-09  本文已影响0人  田成力

箭头函数&数组

箭头函数

特点: 没有 this 没有 arguments 没有prototype
在箭头函数中使用到的以上关键字都是上一级的关键字

数组


// reduce小例子:
let arr = [1, 2, 3, 4, 5];

//pre 上一次reduce返回的结果
//current 当前项
//index 当前项的下标
//arr 原数组
let total = arr.reduce((pre, current, index, arr) => {
  return pre + current;
})
console.log(total);

//小技巧:
// 如何使用reduce将有下面的数组需要求出和
let arr=[{price:10,count:5},{price:10,count:5},{price:10,count:5},{price:10,count:5},{price:10,count:5}]

//如果使用
arr.reduce((pre,current,index,arr)=>{
  return pre.price*pre.count+current.price*current.count;
})
//会发现有bug 因为第二次的pre已经是一个数值了而不是一个对象所以点击price的时候回出现错误
//这时候我们可以,手动的将arr头部添加一个0
let arr=[0,{price:10,count:5},{price:10,count:5},{price:10,count:5},{price:10,count:5},{price:10,count:5}]
arr.reduce((pre,current,index,arr)=>{
  return pre+current.price*current.count;
})


//更优雅的方式:
let arr=[{price:10,count:5},{price:10,count:5},{price:10,count:5},{price:10,count:5},{price:10,count:5}]
arr.reduce((pre,current,index,arr)=>{
  return pre+current.price*current.count;
},0)//手动指定第一项的pre的值

如何实现数组的flat的功能

//flat的功能:
let arr = [1, [2, 3, [4, 5, [6, 7, 8]]]];
let newArr=arr.flat(100)
console.log(newArr);


let arr = [1, [2, 3, [4, 5, [6, 7, 8]]]];



Array.prototype.flat = function () {
  return this.reduce((pre, current, index, arr) => {
    if (Array.isArray(current)) {
      //如果当前项是数组
       pre.push(...current.flat())
       return pre;
    } else {
      console.log(pre);
      console.log(current);
      pre.push(current);
      return pre;
    }
  }, [])
}

 console.log("1111",arr.flat(1000));

利用reduce实现componse的方法

//没有compose函数的用法
function sub(a, b) {
  return a + b;
}

function len(str) {
  return str.length;
}

function addRMB(len) {
  return '$' + len;
}

//想组合调用三个函数
let ret = addRMB(len(sub('abc', 'bcd')));
console.log(ret);


//想要实现:
let ret_compose = compose(addRMB, len, sub)('abc', 'bcd');

function compose(...fns) {
  //找到第一个需要执行的函数
  let lastfn = fns.pop();
  return function (...args) {
   return fns.reduceRight((pre, current) => {
      return current(pre);
    }, lastfn(...args))
  }
}
console.log(ret_compose);

自己实现reduce

  let arr = [{ price: 10, count: 5 }, { price: 10, count: 5 }, { price: 10, count: 5 }];

  Array.prototype.reduce = function (fn, defaultPre) {
    let oldArr = JSON.parse(JSON.stringify(arr));
    let pre = null;
    if (defaultPre != null && defaultPre != undefined) {
      pre = defaultPre;
    } else {
      pre = arr.shift();
    }
    arr.forEach((item, index) => {
      pre = fn(pre, item, index, oldArr);
    });
    return pre;
  }
  let total = arr.reduce((pre, current, index, arr) => {
    return pre + current.price * current.count;
  }, 0)
  console.log(total);

上一篇 下一篇

猜你喜欢

热点阅读