手写数组方法

43 阅读1分钟

1、filter

Array.prototype.filter1 = function (callback, thisArg) {
      if (!Array.isArray(this)) throw new TypeError('this is not an array')
      if (typeof callback !== 'function')
        throw `${typeof callback} ${callback} is not a function`
      const res = []
      for (let i = 0; i < this.length; i++) {
        if (callback.call(thisArg, this[i], i, this)) {
          res.push(this[i])
        }
      }
      return res
    }

2、find

Array.prototype.find1 = function (callback, thisArg) {
      if (!Array.isArray(this)) throw new TypeError('this is not an array')
      if (typeof callback !== 'function')
        throw `${typeof callback} ${callback} is not a function`
      for (let i = 0; i < this.length; i++) {
        if (callback.call(thisArg, this[i], i, this)) {
          return this[i]
        }
      }
    }

3、reduce

Array.prototype.reduce1 = function (callback, initialValue) {
      if (!Array.isArray(this)) throw new TypeError('this is not an array')
      let sum = initialValue || this[0]
      if (typeof callback !== 'function')
        throw `${typeof callback} ${callback} is not a function`
      for (let i = initialValue ? 0 : 1; i < this.length; i++) {
        sum = callback(n, this[i], i, this)
      }
      return sum
    }