緣起:最近看油管裏面有一個關於js面試的視頻,裏面提到了可能會讓你寫一寫reduce等函數,於是也來一起小拔高拔高。
先寫寫map
-
首先回憶平時是如何使用的map。
// const newarr = arr.map(v=>v*v)
-
於是知道我們寫的回調會被map調用,並且傳一個v進來。
Array.prototype.myMap = function (callback){ const newArray = [] this.forEach(ele => { newArray.push(callback(ele)) }) return newArray }
開始寫reduce
-
先上mdn查查reduce的具體參數和用法。
// const afterReduceVal = arr.reduce((acc,cur,idx,src)=>{ do something and return acc},init)
-
也就是說reduce會調用我們的回調,並且傳給我們累加值acc,當前值cur,當前索引idx,源數組src。其中累加值的初始值是我們傳的init,如果我們沒傳,那麼累加值的初始值就會是數組的第一個元素。
Array.prototype.myReduce = function(callback,init) { let acc,idx; if(init){ acc = init // 檢測我們是不是傳了init idx = 0 } else { acc = this[0] idx = 1 } for(let i = idx;i<this.length;i++) { acc = callback(acc,this[i],i,this) } return acc }