js 常用功能函数(持续跟新)

E和弦的根音 · 2020-11-05 · 417 次浏览

1. 存储localStorage

/**
 * 存储localStorage
 * @param {string} name
 * @param {all} content
 * @return {void}
 */
export const setStore = (name, content) => {
  if (!name) return
  content = JSON.stringify(content)
  window.localStorage.setItem(name, content)
}

2. 获取localStorage

/**
 * 获取localStorage
 * @param {string} name
 * @return {all}
 */
export const getStore = (name) => {
  if (!name) return
  const obj = window.localStorage.getItem(name)
  if (obj && obj != 'undefined' && obj != 'null') {
    return JSON.parse(obj)
  }
}

3. 删除localStorage

/**
 * 删除localStorage
 * @param {string} name
 * @return {void}
 */
export const removeStore = (name) => {
  if (!name) return
  window.localStorage.removeItem(name)
}

4. 格式化日期

/**
 * 格式化日期
 * @param {string} fmt
 * @param {date} timestamp
 * @return {string}
 * @example dateFtt('','yyyy-MM-dd hh:mm:ss:SS')
 */
export const dateFtt = (timestamp, fmt='yyyy-MM-dd') => {
  let date = new Date(timestamp)
  var o = {
    'M+': date.getMonth() + 1, //月份
    'd+': date.getDate(), //日
    'h+': date.getHours(), //小时
    'm+': date.getMinutes(), //分
    's+': date.getSeconds(), //秒
    'q+': Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds(), //毫秒
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
  return fmt
}

5. 判断是否是移动设备

/**
 * 判断是否是移动设备
 * @return {boolean}
 */
export const isMobile = () => {
  return (
    navigator.userAgent.match(/Android/i) ||
    navigator.userAgent.match(/webOS/i) ||
    navigator.userAgent.match(/iPhone/i) ||
    navigator.userAgent.match(/iPad/i) ||
    navigator.userAgent.match(/iPod/i) ||
    navigator.userAgent.match(/BlackBerry/i) ||
    navigator.userAgent.match(/Windows Phone/i)
  )
}

6. 下载

/**
 * 下载
 * @param {string} url
 * @param {string} fileName
 * @return {void}
 */
function download(url, fileName = '') {
  let fileUrl = url
  const a = document.createElement('a')
  a.href = fileUrl
  console.log('fileUrl', fileUrl)
  a.target = '_blank'
  a.download = fileName
  console.log('a', a)
  a.click()
}

7. 通过深度连接打开应用程序

/**
 * 通过深度连接打开应用程序
 * @param {string} url
 * @return {Promise}
 */
function openExe(url) {
  let isDone = true
  let timeout = null
  const iframe = document.createElement('iframe')
  const btn = document.createElement('button')
  let p = new Promise((resolve, reject) => {
    btn.onclick = function () {
      launchApplication(
        url,
        function () {
          resolve('success')
        },
        function () {
          reject('fail')
        }
      )
    }
  })

  iframe.style.display = 'none'
  btn.style.position = 'fixed'
  btn.style.top = '-9999px'

  document.body.appendChild(iframe)
  document.body.appendChild(btn)
  btn.click()
  function done() {
    isDone = true
    btn.onblur = null
    iframe.onerror = null
    clearTimeout(timeout)
  }
  function launchApplication(url, success, fail) {
    if (!isDone) return
    isDone = false
    btn.focus()
    btn.onblur = function () {
      if (document.activeElement && document.activeElement !== btn) {
        btn.focus()
      } else {
        console.log('openExe-success')
        done()
        success()
      }
    }
    iframe.onerror = function () {
      done()
      fail()
    }
    try {
      iframe.src = url
    } catch (e) {
      done()
      fail()
      return
    }
    timeout = setTimeout(function () {
      done()
      fail()
    }, 5000)
  }
  return p
}

8. 分钟数转换

/**
 * 分钟数转换
 * @param {number} time
 * @param {boolean} iss
 * @return {Promise}
 */
function (time, iss) {
    if (iss) {
        if (time < 60) {
            return `${time}秒`
        } else if (time > 60 && time < 3600) {
            return `${Math.floor(time / 60)}分钟${Math.ceil(time % 60)}秒`
        } else if (time > 3600) {
            return `${Math.floor(time / 3600)}小时${Math.floor((time % 3600) / 60)}分钟${Math.ceil((time % 3600) % 60)}秒`
        }
    } else {
        if (time < 60) {
            return `${time}分钟`
        } else if (time > 60 && time < 60 * 24) {
            return `${Math.floor(time / 60)}小时${Math.ceil(time % 60)}分钟`
        } else if (time > 60 * 24 && time < 60 * 24 * 365) {
            return `${Math.floor(time / (60 * 24))}天${Math.floor((time % (60 * 24)) / 60)}小时${(Math.ceil(time % (60 * 24)) % 60) %
                60}分钟`
        }
    }
}

9. 数组去重

/**
 * 数组去重
 * @param {array} arr
 * @return {array}
 */
function unique(arr) {
    return Array.from(new Set(arr))
}

10.函数防抖

/**
   * 函数防抖
   * @param func 目标函数
   * @param wait 延迟执行毫秒数
   * @param immediate 是否立即执行
   */
function debounce(func, wait, immediate) {
  let timer
  return function () {
    let context = this,
      args = arguments
    if (timer) clearTimeout(timer)
    if (immediate) {
      let callNow = !timer
      timer = setTimeout(() => {
        timer = null
      }, wait)
      if (callNow) func.apply(context, args)
    } else {
      timer = setTimeout(() => {
        func.apply(context, args)
      }, wait)
    }
  }
}

11.函数节流

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 间隔执行毫秒数
 */
function throttle(func, wait) {
  let previous = 0
  return function () {
    let now = Date.now()
    let context = this
    let args = arguments
    if (now - previous > wait) {
      func.apply(context, args)
      previous = now
    }
  }
}
如果有错误或者不严谨的地方,请务必给予指正,十分感谢。如果喜欢或者有所启发,欢迎评论,对作者也是一种鼓励。
查看评论 - 0 条评论