理解並實現reduce()函數

一、對reduce的理解(聚合)

reduce() 方法對累加器和數組中的每個元素(從左到右)應用一個函數,將其簡化爲單個值。

reduce 接收兩個參數:
   第一個參數是在每一項上調用的函數
該函數接收 4 個參數:
	前一個值 prev
	當前值 cur
	項的索引 index
	數組對象 array
第二個可選參數是作爲歸併基礎的初始值

reduce 方法返回一個最終的值。

實現的過程

  1. 不斷地對數組的前兩項“取出”,對其執行目標函數,計算得到的返回值
  2. 把上述返回值“填回”數組首部,作爲新的 array[0]
  3. 持續循環執行這個過程,直到數組中每一項都訪問了一次
  4. 返回最終結果
二、實現reduce

(1)遞歸實現

const funreduce = (f,acc,arr)=>{
	if(arr.length === 0){
		return acc
	}
	const [head,...tail] = arr
		return funreduce(f,f(acc,head),tail)
}

array.prototype.myreduce = function(fn,initvalue){
	const array = this
	return myreduce(fn,initvalue,array)
}

// 第二版
Array.prototype.fakeReduce = function fakeReduce(fn, base) {

  let initialArr = this;
  let arr = initialArr.concat();

  if (base) arr.unshift(base);
  let index, newValue;

  while (arr.length > 1) {
    index = initialArr.length - arr.length + 1;
    newValue = fn.call(null, arr[0], arr[1], index, initialArr);

    arr.splice(0, 2, newValue); // 直接用 splice 實現替換
  }

  return newValue;
};


//重構非遞歸

Array.prototype.myReduce = function (cb, initialValue) {
  const array = this
  let acc = initialValue || array[0]
  const startIndex = initialValue ? 0 : 1

  for (let i = startIndex; i < array.length; i++) {
    const cur = array[i]
    acc = cb(acc, cur, i, array)
  }
  return acc
}

三、對reduce的應用
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章