实现数组的map,find,fifter方法

286 阅读1分钟

Map方法

Array.prototype.newMap = function (fn, context) {
  let newArray = new Array;
  if (typeof fn !== 'function') {
    throw new TypeError(fn + 'is not function')
  }
  var context = arguments[1];
  for (var i = 0; i < this.length; i++) {
    newArray.push(fn.call(context, this[i], i, this))
  }
  return newArray
}

Find方法

 Array.prototype.newFind = function (fn, context) {
  let str;
  if (typeof fn !== 'function') {
    throw new TypeError(fn + 'is not a function')
  };
  var context = arguments[1];
  for (var i = 0; i < this.length; i++) {
    if (fn.call(context, this[i], i, this)) {
      str = this[i];
      break
    }
  }
  return str
}

fifter方法

Array.prototype.newFilter = function (fn, context) {
  let newArray = new Array;
  if (typeof fn !== 'function') {
    throw new TypeError(fn + 'is not a function')
  }
  var context = arguments[1];
  for (var i = 0; i < this.length; i++) {
    if (fn.call(context, this[i], i, this)) {
      newArray.push(this[i])
    }
  }
  return newArray
}