js常用数组方法的实现

120 阅读1分钟

map方法的实现

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

filter方法的实现

Array.prototype.myFilter = function(func) {
  let newArr = [];
  for (let i = 0;i < this.length; ++i) {
    let returnValue = func(this[i], i);
      returnValue ? newArr.push(returnValue) : '';
    }
  return newArr;
}

forEach方法的实现

Array.prototype.myForEach = function(func) {
  let newArr = [];
  for (let i = 0;i < this.length; ++i) {
    func(this[i], i);
  }
}

push

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

pop

Array.prototype.myPop = function() {
  let popValue = this[this.length-1];
  return this.splice([this.length-1], 1) ? popValue : undefined;
 }

splice

Array.prototype.mySplit = function(index, deleteCount, ...addItem) {
  if (typeof index !== 'number') index = 0;
  else if (index < 0) {
    index = this.length + index;
  }
  const removeItem = this.slice(index, index + deleteCount);
  const startItem = this.slice(0, index);
  const endItem = this.slice(index + deleteCount);
  this.concat(removeItem);
  this.length = 0;
  this.push(...startItem.concat(endItem).concat(addItem));
  return removeItem;
};