ES6数组方法ES5实现、节流防抖

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/m0_37068028/article/details/82901684
  • join
Array.prototype.join = function(arg) {
    let result = this[0] || ''
    const length = this.length
    for (let i = 0; i< length; i++) {
      result += arg + this[i]
    }
    return result
  }
  • slice
  Array.prototype.slice = function(begin, end) {
    let result = []
    begin = begin || 0
    end = end || this.length
    for (let i = begin; i < end; i++) {
      result.push(this[i])
    }
    return result
  }
  • forEach
  Array.prototype.forEach = function(fn) {
    for (let i = 0; i < this.length; i++) {
      if (i in this) {
        fn.call(undefined, this[i], i, this)
      }
    }
  }
  • map
  Array.prototype.map = function(fn) {
    let result = []
    for (let i = 0; i < this.length; i++) {
      if (i in this) {
        result[i] = fn.call(undefined, this[i], i, this)
      }
    }
    return result
  }
  • filter
  Array.prototype.filter = function(fn) {
    let result = []
    let temp
    for (let i = 0; i < this.length; i++) {
      if (i in this) {
        if (temp = fn.call(undefined, this[i], i, this)) {
          result.push(temp)
        }
      }
    }
    return result
  }
  • reduce
  Array.prototype.reduce = function(fn, init) {
    let result = init
    for (let i = 0; i < this.length; i++) {
      if (i in this) {
        result = fn.call(undefined, result, this[i], i, this)
      }
    }
    return result
  }
  a = [1, 2, 3, 4, 5]  
  const result1 = a.reduce( (result, item) => {return result + item}, 0)
  const result2 = a.reduce( (result, item) => {return result + item}, 1)
  console.log(result1)
  console.log(result2)
  • throttle 节流
    降低触发回调的频率,让一个函数不要执行得太频繁,减少一些过快的调用来节流。
    实例: DOM 元素的拖拽功能实现(mousemove)
  var throttle = function(fn, time) {
    let cd = false
    return function() {
      if (cd) {
        return
      }
      fn.call()
      cd = true
      setTimeout(() => {
        cd = false
      }, time)
    }
  }
  • debounce 防抖
    函数去抖就是对于一定时间段的连续的函数调用,只让其执行一次。
    实例:搜索框,向后台发送请求
  var debounce = function(fn, time) {
    let timer = undefined
    return function() {
      if (timer !== undefined) {
        window.clearTimeout(timer)
      }
      timer = setTimeout(() => {
        fn.call()
        timer = undefined
      }, time)
    }
  } 
展开阅读全文

没有更多推荐了,返回首页