先說明一下為什么要寫這個,因為最近在面試,面試的時候面試官問了這個問題,當時是真的沒有答上來,回來之后自己考慮了一下,現在給大家分享
要求如下:
重寫js push函數,使其能夠在push的同時打印出push的元素
分析
有的同學有可能想要用Array.Array.prototype.push = function(){}
來重寫,但是這樣子的話push原本的函數內容就會丟失,你得重寫push的邏輯,這樣就很麻煩。於是我們想到得先把原本的push函數備份一下,然后重寫的時候調用就可以了。
let _push = Array.prototype.push
Array.prototype.push = function(){
for(let i of arguments){
_push.call(this, i);
}
console.log('參數為', arguments);
}
let a = [1,2,3]
a.push(4,5,6)
這個時候控制台已經打印出了我們想要的結果
參考文檔
- MDN web文檔 👉