修改pop方法

111 阅读1分钟

#要求把删除的数据当做新数组返回

var ary = [1,2,3,4,5];
Array.prototype.pop = function (n=1){
    n = n>this.length ? this.length : n;
    temp = this.slice(this.length - n);
    this.length -= n;
    
    return temp;
}
/*上面的三元也可以换成if条件语句*/
if(n >this.length){
    //throw new Erroe('长度不对')
    //temp = this.length(0);//复制这个数组
    temp.push(...this)
}else{
    temp = this.slice(this.length -n);
    this.length -= n;
}