前端JavaScript工具函数汇总

这篇博客探讨了JavaScript中数字加千分号的实现,日期格式化的功能以及图片文件转Base64的过程。通过函数`microMeter`,实现了将数字添加千分号的功能,确保易于读取。`formateDate`函数用于按指定格式展示日期和时间。此外,还介绍了如何使用`turnBase64`函数将图片文件转换为Base64编码,以便在网络中传输。
摘要由CSDN通过智能技术生成

…待续

1. 数字加千分号
function microMeter(n) {
  if (!n) return
  let numStr = n.toString()
  let pointRight = ''
  numStr.indexOf('.') > -1 ? pointRight = '.' + numStr.split('.')[1] : pointRight // pointRight为小数
  pointLeft = numStr.split('.')[0] // pointLeft为整数
  let leftLength = pointLeft.length // leftLength为整数的长度
  if (leftLength <= 3) { // 整数小于3位数,不用加千分号
    return numStr
  } else {
    let remainder = leftLength % 3
    if (remainder > 0) {
      return pointLeft.slice(0, remainder) + ',' + pointLeft.slice(remainder, leftLength).match(/\d{3}/g).join(',') + pointRight
    } else {
      return pointLeft.slice(0, leftLength).match(/\d{3}/g).join(',') + pointRight
    }
  }
}
console.log(microMeter(1234567890.12345))
2. 日期格式化
function formateDate(date, fmt = 'yyyy-MM-dd hh:mm:ss') {
  if (!date) {
    return ''
  }
  date = typeof date === 'number' ? (new Date(date)) : date
  const 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 (let 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
}
3. 图片文件转base64
function turnBase64(file, callBack) {
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = e => {
    callBack(e.target.result) // 返回图片的base64地址
  }
}
turnBase64(options.file, (res) => {
  let infoUrl = res // 得到图片的base64地址
})
4. 获取当天的0点和24点
let startTime1 = new Date(new Date(new Date().toLocaleDateString()).getTime()); // 当天0点
let endTime1 = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1);// 当天23:59
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值