数组push、pop、shift、unshift的模拟实现

  • Post author:
  • Post category:其他


Array.prototype.myPush = function (val) {
  const arr = this;
  arr[arr.length] = val;
  return arr.length;
};

Array.prototype.myPop = function() {
  if (!this.length) {
    return undefined;
  }
  const val = this[this.length - 1];
  this.length -= 1;
  return val;
}
Array.prototype.myShift = function () {
  const arr = this;
  const val = arr[0];
  for (var i = 0; i < arr.length; i++) {
    arr[i] = arr[i + 1];
  }
  arr.length -= 1;
  return val;
};

Array.prototype.myUnshift = function (val) {
  if (!this.length) {
    return undefined;
  }
  const arr = this;
  const result = [];
  result[0] = val;
  for (let i = 0; i < arr.length; i++) {
    result.push(arr[i])
  }
  return result;
};



版权声明:本文为qq_44162474原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。