如何手写一个数组遍历方法

67 阅读1分钟
  // Polyfill: 填充 / 替代
  // forEach
  // Array.prototype.forEach = Array.prototype.forEach || function () { }

  // 自己造一个 forEach
  // const o = { age: 18 };
  // 第一个参数是一个函数
  // 第二个参数是内部 this 的指向
  /* ['a', 'b', 'c'].forEach(function (item, index, originArr) {
    console.log(item, index, originArr, this)
  }, o); */

  /* Array.prototype.forEach2 = function (callback, _this) {
    // 调用 callback
    // this => ['a', 'b', 'c']
    for (let i = 0; i < this.length; i++) {
      callback.call(_this, this[i], i, this) // window.callback()
    }
  };
  ['a', 'b', 'c'].forEach2(function (item, index, originArr) {
    console.log(item, index, originArr, this)
  }, o); */

  /* Array.prototype.map2 = function (callback) {
    const arr = []
    for (let i = 0; i < this.length; i++) {
      arr.push(callback(this[i], i, this))
    }
    return arr
  }
  // map
  const newArr = ['a', 'b', 'c'].map2((item, index, originArr) => {
    // 把这个函数返回的结果放到新数组
    return '~' + item + '~'
  });
  console.log(newArr) */

  /* Array.prototype.filter2 = function (callback) {
    const arr = []
    for (let i = 0; i < this.length; i++) {
      if (callback(this[i], i, this)) {
        arr.push(this[i])
      }
    }
    return arr
  }
  // map
  const newArr = [1, 3, 5].filter2((item, index, originArr) => {
    // 当这个函数的返回结果是 true 的时候,就保留 item 到新数组
    return item >= 3
  });
  console.log(newArr) */