手写实现部分数组方法( map \ filter \some \ reduce \ reverse)

94 阅读2分钟

1.map实现

map 实现步骤:

1.判断调用对象arr是否为数组以及传入参数fn是否为函数。

2.创建一个新数组newArr。

3.循环遍历,使数组arr的每一项调用参数函数fn。

  1. 让fn的this指向传入的第二个参数context。

5.将每一项所得结果推入新数组newArr

6.返回新数组newArr。

Array.prototype.myMap = function (fn, context) {
  const arr = this;  //调用map的数组
  if (!Array.isArray(arr) || typeof fn !== 'function') {
      console.error("type error");
  } else {
      let newArr = [];
      for (let i = 0; i < arr.length; i++) {
          const newItem = fn.call(context,arr[i], i, arr);
          newArr.push(newItem)
      }
      return newArr;
  }
}

2.filter实现

filter 实现步骤:

1.判断调用对象arr是否为数组以及传入参数fn是否为函数。

2.创建一个新数组newArr。

3.循环遍历,使数组arr的每一项调用参数函数fn。

4.让fn的this指向传入的第二个参数context。

5.如果结果不为0,则将此项推入新数组newArr。

6.返回新数组newArr。

Array.prototype.myFilter = function (fn, context) {
  const arr = this; 
  if (!Array.isArray(arr) || typeof fn !== 'function') {
      console.error("type error");
  } else {
      let newArr = [];
      for (let i = 0; i < arr.length; i++) {
          const res = fn.call(context, arr[i], i, arr);
          if (res) newArr.push(arr[i]);
      }
      return newArr;
  }
}

3. some实现

some 实现步骤:

1.判断调用对象arr是否为数组以及传入参数fn是否为函数。

2.循环遍历,使数组arr的每一项调用参数函数fn。

3.让fn的this指向传入的第二个参数context。

4.如果某项结果为true,则直接返回true。

5.否则,返回false。

Array.prototype.mySome = function (fn, context) {
  const arr = this; 
  if (!Array.isArray(arr) || typeof fn !== 'function') {
      console.error("type error");
  } else {
      for (let i = 0; i < arr.length; i++) {
          const newItem = fn.call(context, arr[i], i, arr);
          if (newItem) return true;
      }
      return false;
  }
}

4. reduce实现

reduce 实现步骤:

1.判断调用对象arr是否为数组以及传入参数fn是否为函数。

2.判断是否传入初始值,无则为0。

3.循环遍历,使数组arr的每一项调用参数函数fn。

4.前一项的返回结果作为下一项的第一个参数传入。

5.返回最终结果。

Array.prototype.myReduce = function (fn, initialValue) {
  const arr = this; 
  if (!Array.isArray(arr) || typeof fn !== 'function') {
      console.error("type error");
  } else {
      let res = (initialValue === undefined) ? 0 : initialValue;
      for (let i = 0; i < arr.length; i++) {
           res = fn(res, arr[i], i, arr);         
      }
      return res;
  }
}

5.reverse实现

reverse 实现步骤:

1. 判断调用对象arr是否为数组。

2.取数组第一个值和最后一个值,将两个调换。

3.同步依次向里移动,两两调换,至数组中间位置。

4.返回处理后的arr。

Array.prototype.myReverse = function () {
  let arr = this;
  if (!Array.isArray(arr)) {
      console.error("type error");
  } else {
      let left = 0, right = arr.length - 1;
      while (left < right) {
          let temp = arr[left];
          arr[left] = arr[right];
          arr[right] = temp;
          left++;
          right--;
      }
  }
  return arr;
}