手写ES6数组方法

Array.prototype.customMap = function (fn) {
  let newArr = [];
  for (let i = 0, l = this.length; i < l; i++) {
    newArr.push(fn(this[i]), i, this)
  }
  return newArr;
}
Array.prototype.customFilter = function (fn) {
  let newArr = [];
  for (let i = 0, l = this.length; i < l; i++) {
    if (fn(this[i])) {
      newArr.push(fn(this[i], i, this))
    }
  }
  return newArr;
}
Array.prototype.customSort = function (fn) {
  let t;
  fn = fn || function (a, b) {
    return a - b;
  }
  for (let i = 0, l = this.length; i < l; i++) {
    for (let j = i; j < l; j++) {
      if (fn(this[i], this[j]) > 0) {
        t = this[i];
        this[i] = this[j];
        this[j] = t;
      }
    }
  }
}
Array.prototype.customReduce = function (fn) {
  if (!this.length) {
    throw 'no value'
  }
  let prev = 0;
  for (let i = 0, l = this.length; i < l; i++) {
    prev = fn(prev, this[i], i, this);
  }
  return prev;
}
Array.prototype.customFrom = function (obj) {
  return [].slice.call(obj)
};
posted @ 2020-05-06 17:51  哥哦狗子  阅读(215)  评论(0编辑  收藏  举报