js中Array方法重写(一):myPush(),myPop(),myUnshift(),myShift()

一、myPush()

//myPush() 数组入栈
Array.prototype.myPush = function(){
    var L = this.length;
    for(var i = L ; i < L + arguments.length ; i++){
        this[i] = arguments[i - L];
    }
    return this.length;
}

二、myPop()

//Mypop() 数组出栈
Array.prototype.myPop = function(){
    if (this.length == 0) {
        return undefined;
    }
    var last = this[this.length-1];
    this.length = this.length-1;
    return last;
}

三、myUnshitf()

//myUnshift 数组入队
Array.prototype.myUnshift = function(){
    var L = this.length;
    for(var i = L + arguments.length - 1 ; i >= 0 ; i--){
        if(i > arguments.length - 1){
            this[i] = this[i - arguments.length];
        }else{
            this[i] = arguments[i];
        }
    }
    return this.length;
}

四、myShitf()

//myShift()数组出队
Array.prototype.myShift = function(){
    if (this.length == 0) {
        return undefined;
    }
    var firstElement = this[0];
    for(var i = 1 ; i < this.length ; i++){
        this[i-1] = this[i];
    }
    this.length = this.length-1;
    return firstElement;
}

纯手写,如有不善,请指正 ^_^

    原文作者:yuan
    原文地址: https://segmentfault.com/a/1190000014742895
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞