js常用数组方法的实现

2019-07-16  本文已影响0人  心大的少年

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;
 }
上一篇 下一篇

猜你喜欢

热点阅读