reduce方法的封装使用

reduce()方法

语法:

    arr.reduce(
        function(previousValue, item, index, arr) {

        }, initialValue)
  • previousValue:上一次调用回调函数时的返回值,或者初始值

  • currentValue:当前正在处理的数组元素

  • currentIndex:当前正在处理的数组元素下标

  • array:调用reduce()方法的数组

  • initialValue:可选的初始值(作为第一次调用回调函数时传给 previousValue 的值)

eg:

  var arr = ['a', 'b', 'c', 'd'];
  result = arr.reduce(function (pre, item) {
          console.log('pre: '+ pre + ';item: '+ item);
          return pre+item;          
  });
  console.log('result: ' + result);

              

依次对数组内每个元素执行回调函数

--------------------------------------------------------------------

 封装方法:

  //往数组原型添加一个myReduce方法
  Array.prototype.myReduce = function (fn, init){
  //fn为回调函数,init为初始值
  var len = this.length,
     pre = init,
     i = 0;
  //判断初始值的类型
  if (init == undefined) {
    pre = this[0];
    i = 1;
  };
  //pre   
for (var i = 0; i < len; i++){     pre = fn (pre, this[i], i, this) //function(previousValue, item, index, arr)   };   return pre; }
    arr.myReduce(function (pre, ele, index, arr) {
            console.log(pre, ele, index, arr);
            return pre+ele;
        },'g');

结果:

      

猜你喜欢

转载自www.cnblogs.com/dongrui23/p/11877416.html