js常用工具函数

时间:2021-03-01 19:32:16

1、本地存储

export const LocalStorage = {
  get(name) {
    return JSON.parse(localStorage.getItem(name))
  },
  set(name, val) {
    localStorage.setItem(name, JSON.stringify(val))
  }
}

2、会话存储

export const SessionStorage = {
  get(name) {
    return JSON.parse(sessionStorage.getItem(name))
  },
  set(name, val) {
    sessionStorage.setItem(name, JSON.stringify(val))
  }
}

3、判断是否为ie浏览器

/**
 * 判断是否为ie浏览器
 */
export function IEVersion() {
  let userAgent = navigator.userAgent
  let isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1
  let isEdge = userAgent.indexOf("Edge") > -1 && !isIE
  let isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1
  if (isIE) {
    let reIE = new RegExp("MSIE (\\d+\\.\\d+);")
    reIE.test(userAgent)
    let fIEVersion = parseFloat(RegExp["$1"])
    if (fIEVersion == 7) {
      return 7
    } else if (fIEVersion == 8) {
      return 8
    } else if (fIEVersion == 9) {
      return 9
    } else if (fIEVersion == 10) {
      return 10
    } else {
      return 6 //IE版本<=7
    }
  } else if (isEdge) {
    return 'edge' //edge
  } else if (isIE11) {
    return 11
  } else {
    return -1 //不是ie浏览器
  }
}

4、获取url地址参数对象

/**
 * 获取url地址参数对象
 * @param {String} search 查询的URL字符串
 */
export function getUrlParams(search) {
  let url = search || location.href
  let theRequest = {}
  if (url.indexOf("?") != -1) {
    let str = url.substr(url.indexOf("?") + 1)
    let strs = str.split("&")
    for(let i = 0; i < strs.length; i++) {
      let [k, v] = strs[i].split("=")
      theRequest[k] = decodeURIComponent(v)
    }
  }
  return theRequest
}

5、节流控制

/**
 * 节流控制
 * @param {Function} func 需要执行节流控制的方法
 * @param {Number} delay 延时时间,单位毫秒
 */

export function throttle(func, delay) {
  let timer = null
  let startTime = Date.now()
  return function(){
    let curTime = Date.now()
    let remaining = delay - (curTime - startTime)
    let self = this
    let args = arguments
          

    clearTimeout(timer)
    if(remaining <= 0){
      func.apply(self, args)
      startTime = Date.now()
    }else{
      timer = setTimeout(() => {
        func.apply(self, args)
      }, remaining)
    }
  }
}