首页 > 不用数组操作方法实现数组的`pop`、`push` 方法

不用数组操作方法实现数组的`pop`、`push` 方法

如题,包括实现pop push 的返回值


push 的实现:

function pushArr(arr, value) {
  arr[arr.length] = value;
  return arr;
}
var arr = [];
pushArr(arr, 1);

pop 的实现:

function popArr(arr) {
  if(arr.length === 0) return undefined;
  var temp = arr[arr.length-1];
  arr.length--;
  return temp;
}

var arr = [1,2,3,4,5,6];
popArr(arr);

Array.prototype._push = function(item) {
    this[this.length] = item;
    return this.length;
}


Array.prototype._pop = function() {
    if (this.length === 0) return void 0;
    var temp = this[this.length - 1];
    this.length--;
    return temp;
}
【热门文章】
【热门文章】