JavaScript常用工具函数

211 阅读3分钟

本地存储

js存储有localstorage、sessionStorage、cookie 三种,相同点都是保存浏览器端的。不同点主要有以下几点:

  1. 大小不同
    • cookie 大小不超过4K,而localstorage、sessionStorage则大得多,可以达到5M或者更多
  2. 传递方式不同
    • localstorage、sessionStorage仅存在本地,不会传递给服务端。
    • cookie会在浏览器与服务端来回传递。
  3. 数据作用域不同
    • localstorage、cookie 在同源窗口中共享。
    • sessionStorage 不在不同浏览器窗口中共享。
  4. 数据有效周期
    • localstorage是将数据存储在本地,需要手动删除,持久保存。
    • 而存储在sessionStorage里面的数据,在浏览器窗口关闭的时候,自动删除。
    • cookie 在设置的过期时间之前都是有效的。
  • localstorage存储数据:
/**
 * 将value以key为键保存到localStorage中
 * @param { string } name 存储到localStorage的key
 * @param { any } value 存储到localStorage的value
 * @returns { void }
 */
export const setStorageItem = (name, value) => {
  if (!name) return
  return window.localStorage.setItem(name, JSON.stringify(value))
}
  • localstorage获取存储数据:
/**
 * 根据key获取localStorage的值
 * @param {string} name localStorage中存储的key
 * @returns { any } 找到就返回,未找到就返回undefined
 */
export const setStorageItem = (name, value) => {
  if (!name) return
  return window.localStorage.setItem(name, JSON.stringify(value))
}
  • 移除localstorage中某项数据:
/**
 * 删除localStorage
 * @param {string} name 删除localStorage中对应的key
 */
export const removeStorageItem = (name) => {
  if (!name) return
  return window.localStorage.removeItem(name)
}
  • 清空localstorage:
// 将本地localstorage存储的数据全部清空
export const clearStorage = () => window.localStorage.clear()
  • sessionStorage数据存储:
/**
 * @param {String} key  属性  存储的键
 * @param {*} value 值  存储的值
 */
export const sessionStorageSet = (key, value) => {
  if (typeof (value) === 'object') value = JSON.stringify(value)
  sessionStorage.setItem(key, value)
}
  • 获取sessionStorage存储的数据:
/**
 * @param {String} key  属性
 */
export const sessionStorageGet = (key) => { return sessionStorage.getItem(key) }
  • 移除 sessionStorage 存储的某项数据:
/**
 * @param {String} key  属性
 */
export const sessionStorageRemove = (key) => { sessionStorage.removeItem(key) }
  • 清空 sessionStorage:
// 将sessionStorage存储的数据全部清空
export const clearSessionStorage = () => window.sessionStorage.clear()

下载流文件

一般情况下,前端导出的Excel,后端都是返回的文件流格式,前端需要对格式进行转化,然后使用 a 标签进行下载。

/**
 * 导出Excel文件
 * @param res 后端返回的文件流
 * @param fileName  设置的文件名称
 */
export const exportExcel = (res, fileName) => {
  const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
  const objectUrl = URL.createObjectURL(blob)
  // 兼容IE
  if (!!window.ActiveXObject || 'ActiveXObject' in window) navigator.msSaveBlob(blob, fileName) else {
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = objectUrl
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href) // 释放URL 对象
    document.body.removeChild(elink)
  }
}

获取文件后缀名

/**
 * 获取文件的后缀名
 * @param fileName
 * @returns {string}
 */
export const getSuffixName = (fileName) => {
  if (!fileName) return null
  const index = fileName.lastIndexOf('.')
  const suffix = fileName.substr(index + 1)
  return suffix.toLowerCase()
}

已过时间

/**
 * @desc   格式化${startTime}距现在的已过时间
 * @param  {Date} startTime
 * @return {String}
 */
export const formatPassTime = (startTime) => {
  let currentTime = Date.parse(new Date()),
      time = currentTime - startTime,
      day = parseInt(time / (1000 * 60 * 60 * 24)),
      hour = parseInt(time / (1000 * 60 * 60)),
      min = parseInt(time / (1000 * 60)),
      month = parseInt(day / 30),
      year = parseInt(month / 12)
  if (year) return `${year}年前`
  if (month) return `${month}个月前`
  if (day) return `${day}天前`
  if (hour) return `${hour}小时前`
  if (min) return `${min}分钟前`
  else return '刚刚'
}

剩余时间

/**
 * @desc   格式化现在距${endTime}的剩余时间
 * @param  {Date} endTime
 * @return {string}
 */
export const formatRemainTime = (endTime) => {
  let startDate = new Date() //开始时间
  let endDate = new Date(endTime) //结束时间
  let t = endDate.getTime() - startDate.getTime() //时间差
  let d = 0,
      h = 0,
      m = 0,
      s = 0
  if (t >= 0) {
    d = Math.floor(t / 1000 / 3600 / 24)
    h = Math.floor(t / 1000 / 60 / 60 % 24)
    m = Math.floor(t / 1000 / 60 % 60)
    s = Math.floor(t / 1000 % 60)
  } else {
    return '0'
  }
  return `${d}${h}小时${m}分钟${s}秒`
}

金额大写转化

/**
 * 金额大写转换
 * 例如: 52632 result:"伍万贰仟陆佰叁拾贰元整"
 * -1693 欠壹仟陆佰玖拾叁元整
 * @param n  传入数字金额
 * @returns {string}
 */
export const upDigit = (n) => {
  let fraction = ['角', '分', '厘']
  let digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  let unit = [
    ['元', '万', '亿'],
    ['', '拾', '佰', '仟']
  ]
  let head = n < 0 ? '欠' : ''
  n = Math.abs(n)
  let s = ''
  for (let i = 0; i < fraction.length; i++) s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '')
  s = s || '整'
  n = Math.floor(n)
  for (let i = 0; i < unit[0].length && n > 0; i++) {
    let p = ''
    for (let j = 0; j < unit[1].length && n > 0; j++) {
      p = digit[n % 10] + unit[1][j] + p
      n = Math.floor(n / 10)
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
  }
  return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整')
}

清除对象中值为空的属性

/**
 * 清除对象中值为空的属性
 * @param obj 传入的对象
 * @returns {{}}
 */
export const filterParams = (obj) =>{
  let newObj = {}
  for (let key in obj) if ((obj[key] === 0 || obj[key] === false || obj[key]) && obj[key].toString().replace(/(^\s*)|(\s*$)/g, '') !== '') newObj[key] = obj[key]
  return newObj
}

获取URL中的参数


/**
 * 获取url链接中参数
 * @param  {String} url
 * @param  [String] key 参数名。可选
 * @return {String|Object}
 */
export const getQueryString = (url = '', key) => {
  const search = url.split('?').pop()
  if (search && search.length) {
    const result = {}
    const items = search.split('&')
    for (let item of items) {
      const entry = item.split('=')
      const name = decodeURIComponent(entry[0])
      if (name) result[name] = decodeURIComponent(entry[1])
    }
    return key ? result[key] : result
  }
  return null
}
  • 持续更新中。。。。