原生JS數組方法實現(一)————push()、unshift()、pop()和shift()

push

向數組末尾添加一個或多個元素,並返回數組新的長度html

function push(){ for(let i=0;i<arguments.length;i++){ this[this.length] = arguments[i]; } return this.length } Array.prototype.push = push;

unshift

向數組開頭添加一個或多個元素,而且返回數組新的長度數組

function unshift(){ //建立一個新數組接收添加的元素
    let newAry = []; for(let i=0;i<arguments.length;i++){ newAry[i] = arguments[i]; } let len = newAry.length; for(let i=0;i<this.length;i++){ newAry[i+len] = this[i]; } for(let i=0;i<newAry.length;i++){ this[i] = newAry[i]; } return this.length; } Array.prototype.unshift = unshift;

pop

刪除數組最後一項,並返回該刪除項目this

function pop(){ let returnVal = this[this.length-1]; this.length--; return returnVal } Array.prototype.pop = pop;

shift

刪除數組第一項,而且返回該刪除項目spa

function shift(){ let newAry = []; let reVal = this[0]; for(let i=0;i<this.length-1;i++){ newAry[i] = this[i+1]; } for(let i=0;i<newAry.length;i++){ this[i] = newAry[i] } this.length--; return reVal; } Array.prototype.shift = shift;

```prototype

原文出處:https://www.cnblogs.com/bxbxb/p/12142167.htmlcode

相關文章
相關標籤/搜索