js常用处理函数

整理一下开发中常用的一些小工具处理函数

  • 复制文字
function copyText (value) {
  if (!value) return
  // 新方式 - 兼容性问题, 以及权限问题(慎用)
  navigator.clipboard.writeText(value).then(() => {
      Message.success('复制成功')
  });
  // 旧方式, 已废弃
  const oInput = document.createElement('input')
  oInput.value = value
  document.body.appendChild(oInput)
  oInput.select()
  oInput.setSelectionRange(0, value.length) // ios 必须加这个
  document.execCommand('Copy')
  oInput.remove()
  Message.success('复制成功')
}
  • 深拷贝处理
function deepClone (obj) {
  // 判断拷贝的要进行深拷贝的是数组还是对象,是数组的话进行数组拷贝,对象的话进行对象拷贝
  const objClone = Array.isArray(obj) ? [] : {}
  // 进行深拷贝的不能为空,并且是对象或者是
  if (obj && typeof obj === 'object') {
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (obj[key] && typeof obj[key] === 'object') {
          objClone[key] = deepClone(obj[key])
        } else {
          objClone[key] = obj[key]
        }
      }
    }
  }
  return objClone
}
  • 秒数转 ==> 时:分:秒
function secondFormate (t) {
  if (!t) return;
  let i
  let a
  if (t < 60) return "00:" + ((i = t) < 10 ? "0" + i : i);
  if (t < 3600) return String((a = parseInt(t / 60)) < 10 ? "0" + a : a) + ":" + ((i = t % 60) < 10 ? "0" + i : i);
  if (t >= 3600) {
    const e = parseInt(t / 3600);
    return (e < 10 ? "0" + e : e) + ":" + ((a = parseInt(t % 3600 / 60)) < 10 ? "0" + a : a) + ":" + ((i = t % 60) < 10 ? "0" + i : i);
  }
}
  • 时间格式化
function timeFormat (tem, fmt = 'yyyy-MM-dd HH:mm:ss') {
  let ret;
  const date = tem ? new Date(tem) : new Date()
  const opt = {
    "y+": date.getFullYear().toString(),        // 年
    "M+": (date.getMonth() + 1).toString(),     // 月
    "d+": date.getDate().toString(),            // 日
    "H+": date.getHours().toString(),           // 时
    "m+": date.getMinutes().toString(),         // 分
    "s+": date.getSeconds().toString(),          // 秒
    // 有其他格式化字符需求可以继续添加,必须转化成字符串
  };
  for (const k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, "0"))
    }
  }
  return fmt;
}
  • 生成 [min, max] 的随机数
function random (min, max) {
  return Math.floor(Math.random()*(max-min+1)+min);
}
  • 生成随机码 n-生成码的长度
function randomCoding (n = 8) {
  // 创建26个字母数组
  const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',];
  let idvalue = '';
  for (let i = 0; i < n; i++) {
    idvalue += arr[random(0, arr.length - 1)];
  }
  return idvalue;
}
  • 小数点精准位数处理, 防止出现0.33333333333类似的数字 value-传入要处理的数字 n-精准小数点后的位数
function numFixed (value, n= 2) {
  return Math.round(value * Math.pow(10, n)) / Math.pow(10, n)
}
  • 动态创建a标签下载文件
function aLink (url) {
  if (!url) return
  const link = document.createElement('a')
  link.href = url
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
  • 强导出文件
function aLinkFile (downUrl, fileName) {
  const aLinkUrl = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
  aLinkUrl.href = downUrl
  aLinkUrl.download = fileName
  const clickAlink = (obj) => { // 模拟点击
    const ev = document.createEvent('MouseEvents')
    ev.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
    obj.dispatchEvent(ev)
  }
  clickAlink(aLinkUrl)
}
  • 获取 blob 的返回 值是否成功 streamRes-后端返回的流
  • 当 responseType 设置为blob时, 异常捕获的json也会被转换为blob, 所以处理一下
function isBlobSuccess (streamRes) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.onload = function () {
      try {
        const jsonData = JSON.parse(this.result);  // 说明是普通对象数据,后台转换失败
        if (jsonData.code === 0) {
          Message.error(jsonData && jsonData.msg || '获取文件失败')
          reject(jsonData)
        }
      } catch (err) {   // 解析成对象失败,说明是正常的文件流
        // 文件过小 资源不对
        if (streamRes.size < 100) {
          Message.warning(`没有该资源!`)
          reject(streamRes)
        } else {
          resolve(streamRes)
        }
      }
    };
    fileReader.readAsText(streamRes)
  })
}
  • 滚动到顶部处理 带动画
function scrollTop (duration = 1) {
    if (!duration || duration <= 0) {
      duration = 1
    }
    let elementScrollTop = document.documentElement.scrollTop || document.body.scrollTop
    let tick = elementScrollTop / (duration * 10)
    let timer = setInterval(() => {
      if (document.documentElement.scrollTop <= 0) {
        clearInterval(timer)
      } else {
        document.documentElement.scrollTop = document.documentElement.scrollTop - tick
      }
    }, 10)
  }
  • 滚动到底部
function scrollBottom (duration = 1) {
  if (!duration || duration <= 0) {
    duration = 1
  }
  let elementScrollTop = document.documentElement.scrollHeight || document.body.scrollHeight
  let tick = elementScrollTop / (duration * 10)
  let timer = setInterval(() => {
    if (document.documentElement.scrollTop >= document.documentElement.scrollHeight - document.documentElement.offsetHeight) {
      clearInterval(timer)
    } else {
      document.documentElement.scrollTop = document.documentElement.scrollTop + tick
    }
  }, 10)
}
  • 处理号号码 ****
function starPhone (phone) {
  let reg = /(\d{3})\d*(\d{4})/
  return (phone.replace(reg, '$1****$2') || '--')
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容