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

  • 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)
    }
  } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值