数组方法手写

104 阅读1分钟

filter

Array.prototype.filter( callback(current, index), thisArg)

  • current: 当前元素*
  • index: 当前元素的索引
  • thisArg: 作为回调函数的值

    作用:返回经过符合操作的元素组成的数组

    function myFilter(callback) {
      if (this === undefined) throw new TypeError("this is null or undefined")
      if (! callback instanceof Function) 
        throw new TypeError(callback + " is not a function")
      let result = [] // 定义返回数组
      const that = Object(this)
      
      for(let key in that) {
        if(that.hasOwnProperty(key) && callback.call(that, that[key], key)) 
          result.push(that[key])
      }
​
      return result
    }
​
    const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}];
​
    Array.prototype.filter = myFilter
    const res4 = arr.filter( (item, index) => {
      return arr.indexOf(item) == index
    })
    console.log(res4);

forEach

forEach 是遍历数组,对每一项执行对应的操作,没有返回值

forEach 会改变原数组

    function myForEach(callback) {
      if (this == undefined) throw new TypeError("this is null or undefined")
      if (! callback instanceof Function) throw new TypeError(callback + " is not a function")
      const that = Object(this)
​
      for(let key in that) {
        if(that.hasOwnProperty(key)) {
          callback.call(that, that[key], Number(key)) 
        }
      }
    }

map

map: 一个由原数组中每个元素执行回调的结果组成的新数组

    function myMap(callback) {
      if (this == undefined) throw new TypeError("this is null or undefined")
      if (! callback instanceof Function) throw new TypeError(callback + " is not function")
      const that = Object(this)
      const result = []
      for(let key in that) {
        if (that.hasOwnProperty(key)) {
          result[key] = callback.call(that, that[key], key)
        }
      }
      return result
    }
​
    Array.prototype.map = myMap
    const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}];
    const newArr = arr.map((item, key) => {
      return arr.indexOf(item) % 3 !== 0 
    })
    console.log(newArr);

reduce

reduce 返回函数累计处理的结果

initialValue是调用时第一个参数额值,没写的话默认是数组的第一个有效值

空数组调用报错

      function myReduce(callback, initialValue) {
        if (this == undefined) {
          throw new TypeError("this is null or not defined");
        }
        if (typeof callback !== "function") {
          throw new TypeError(callbackfn + " is not a function");
        }
​
        const that = this;
        let preValue = initialValue;
        let key = 0
        // 当没有传第一个值时,使用数组的第一个有效值
        if (preValue === undefined) {
          for (; key < that.length; key ++) {
            if (!preValue && !that.includes(preValue)) {
              preValue = that[key] === undefined ? undefined : that[key];
              key = key === 0 ? 1 : key
              break
            }
          }
        }
        if (preValue === undefined)
          throw new TypeError("Reduce of empty array with no initial value");
        for (; key < that.length; key ++) {
          preValue = callback.call(undefined, preValue, that[key], key);
        }
        return preValue;
      }
​
      const arr = [1, 2, 3, 4];
      Array.prototype.reduce = myReduce;
​
      
      const res = arr.reduce((pre, cur) => {
        return pre + cur;
      });
​
      console.log(res);