实现forEach、map、reduce、filter、indexOf、jion手写

200 阅读1分钟

实现foreach

Array.prototype.myForEach = function (fn, context = null) {
  let index = 0;
  let arr = this;
  if (typeof fn !== 'function') {
    throw new TypeError(fn + 'is not a function');
  }
  while (index < arr.length) {
    if (index in arr) {
      fn.call(context, arr[index], index, arr)
    }
    index++
  }
}

实现map

Array.prototype.mymap = function (fn, context = null) {
  let arr = this;
  let len = arr.length;
  let index = 0;
  let newArr = [];
  if (typeof fn !== 'function') {
    throw new TypeError(fn + ' is not a function');
  }
  while (index < len) {
    if (index in arr) {
      let result = fn.call(context, arr[index], index, arr);
      newArr[index] = result; // 返回值作为一个新数组
    }
    index++;
  }
  return newArr;
};

实现reduce

Array.prototype.myreduce = function (...arg) {
  let arr = this;
  let len = arr.length;
  let index = 0;
  let fn = arg[0], result;
  if (arg.length >= 2) { // 判断是否有第二个参数,有的话作为回调函数运行的初始值
    result = arg[1];
  } else {
    // reduce 在没有第二个参数的时候,会把数组的第一项作为回调的初始值
    // 第一项并不一定是 a[0]
    while (index < len && !(index in arr)) {
      // 下标小于数组长度且下标不属于该数组就一直循环,用来找到数组的第一项
      index++;
    }
    if (index >= len) { // 如果第一项大于等于数组长度,则说明是空数组
      throw new TypeError('空数组且没有初始值');
    }
    result = arr[index++]; // 赋值之后下标+1
  }
  if (typeof fn !== 'function') {
    throw new TypeError(fn + ' is not a function');
  }
  while (index < len) {
    if (index in arr) {
      result = fn(result, arr[index], index, arr); // 每次回调的返回值,都会传入下次回调
    }
    index++;
  }
  return result;
};

实现filter

Array.prototype.myfilter = function (fn, context = null) {
  let arr = this;
  let len = arr.length;
  let index = 0, k = 0;
  let newArr = [];
  if (typeof fn !== 'function') {
    throw new TypeError(fn + ' is not a function');
  }
  while (index < len) {
    if (index in arr) {
      let result = fn.call(context, arr[index], index, arr);
      if (result) newArr[k++] = arr[index]; // 如果返回值为真,就添加进新数组
    }
    index++;
  }
  return newArr;
};

实现indexOf

Array.prototype.myindexOf = function (val, fromIndex = 0) {
  let arr = this;
  let len = arr.length;
  let k = Math.max(fromIndex >= 0 ? fromIndex : len - Math.abs(fromIndex), 0);
  // 处理负数
  while (k < len) {
    if (k in arr) {
      if (val === arr[k]) return k; // 找到返回下标
    }
    k++;
  }
  return -1; // 找不到返回 -1
};

实现jion

Array.prototype.myjoin = function (connector = ',') {
  let arr = this;
  let len = arr.length;
  let str = '';
  let k = 0;
  while (k < len) {
    if (k in arr) {
      if (k === len - 1) { // 最后一位不用连接
        str += arr[k];
      } else {
        str += arr[k] + connector.toString();
      }
    }
    k++;
  }
  return str;
};