Native JS array implemented method (a) ---- push (), unshift (), pop () and shift ()

push

Add one or more elements to the end of the array, and returns the new length of the array

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

unshift

Add one or more elements to the beginning of the array, and returns the new length of the array

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

Delete an array of the last item, and returns the deleted items

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

shift

Delete the first array, and returns the deleted items

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;

```

Guess you like

Origin www.cnblogs.com/bxbxb/p/12142167.html