1. 程式人生 > >ES6陣列方法ES5實現、節流防抖

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)
    }
  }