认识reduce的强大,实现一个简单reduce

不一样与其余遍历数组的方法,reduce能够返回任意的类型,更加的灵活。数组

认识reduce

Array.reduce(callback,starValue)接受两个参数,并返回一个最后的累加值(与starValue同一类型)markdown

  • callback:对数组每一个元素都执行的回调方法。函数

  • starValue:初始值(能够是任意类型)。this

callback(accumulator,current,currentInedex,arr) 接收四个参数:当前的累加结果、当前要累加的值、当前索引、数组自己spa

使用reduce 实现数组求和

var total = [1, 2, 3].reduce(function (accumulator, current) {
  return accumulator + current;
}, 0);

console.log(total) // 6
复制代码

使用reduce实现遍历数组中的对象,获取对象中符合条件的值并返回一个数组

const arr = [
  {
    name: 'lgf',
    age: 22
  },
  {
    name: 'chm',
    age: 22
  },
  {
    name: 'lalal',
    age: 21
  }
]

var newArr = arr.reduce(function (accumulator, current) {
  if (current.age === 22) {
    accumulator.push(current.name);
  }
  return accumulator;
}, []);

console.log(newArr) // ["lgf", "chm"]
复制代码

从数组生成 HTML 标签(返回字符串类型)

var nameList = arr.reduce(function (accumulator, current) {
  if (current.age === 22) {
    accumulator += '<li>' + current.name + '</li>';
  }
  return accumulator;
}, '');
console.log(nameList) // <li>lgf</li><li>chm</li>

复制代码

累加一个对象

var newArr = arr.reduce(function (accumulator, current) {
  if (current.age === 22) {
    const type = current.name
    accumulator[type]=current.name;
  }
  return accumulator;
}, {});

console.log(newArr) // {lgf: "lgf", chm: "chm"}
复制代码

最后 让咱们来实现一个reduce方法

Array.prototype.myReduce = function(fn, initialValue) {
 // 由于是数组调用 myReduce方法因此this指向当前数组
 // 初始化要返回累加值: 若是有传初始值则acc的初始值为initialValue,不然为数组的第一个个值
 let acc = initialValue || this[0]
 
 // 定义开始计算的索引:若是有传初始值则为0,不然为1
 const startIndex = initialValue ? 0 : 1
 
 // 遍历数组 执行传进来的函数(四个参数,前两个是重点,1:当前累加总和,2:当前要累加的值,3:当前要累加值的索引,4:当前的数组)
 for (let i = startIndex; i < this.length; i++) {
     acc = fn(acc, this[i], i, this)
 }
 
 // 返回累加值
 return acc
}
复制代码

判断参数是否合法:prototype

Array.protopy.myReduce = function(fn,value){
    if(typeof fn !== 'function'){
         console.log('第一个参数必须为一个函数')
         return 
    }
    const acc =  value || this[0];
    const startIndex = value ? 0 : 1
    for(let i = startIndex; this.length,i++){
       acc = fn(acc, this[i], i, this)
    }
    return acc
}
复制代码
相关文章
相关标签/搜索