开发中必备工具函数指南(持续更新中...)赶紧点赞收藏

92 阅读2分钟

1.判断是否是微信浏览器

function isWeixin () {
  let ua = navigator.userAgent.toLowerCase()
  return ua.indexOf("micromessenger") != -1
}

2. 判断一个对象是否是空对象

方法一:

Object.keys(obj).length === 0

方法二:

JSON.stringify(obj) === '{}'

3. js中计算精度丢失的处理方法:

两数相加精度丢失

function numAdd(num1: number, num2: number) {
  let baseNum, baseNum1, baseNum2
  try {
    baseNum1 = num1.toString().split('.')[1].length
  } catch (e) {
    baseNum1 = 0
  }
  try {
    baseNum2 = num2.toString().split('.')[1].length
  } catch (e) {
    baseNum2 = 0
  }
  baseNum = Math.pow(10, Math.max(baseNum1, baseNum2))
  return (num1 * baseNum + num2 * baseNum) / baseNum
}

两数相减精度丢失

function numSubtr(num1, num2) {
  let baseNum, baseNum1, baseNum2
  try {
    baseNum1 = num1.toString().split('.')[1].length
  } catch (e) {
    baseNum1 = 0
  }
  try {
    baseNum2 = num2.toString().split('.')[1].length
  } catch (e) {
    baseNum2 = 0
  }
  baseNum = Math.pow(10, Math.max(baseNum1, baseNum2))
  // 动态控制精度长度
  const n = baseNum1 >= baseNum2 ? baseNum1 : baseNum2
  return Number(((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(n))
}

两数相乘精度丢失

function numMulti(num1, num2) {
    let baseNum = 0;
    try {
      baseNum += num1.toString().split(".")[1].length;
    } catch (e) {}
    try {
      baseNum += num2.toString().split(".")[1].length;
    } catch (e) {}
    return (
      (Number(num1.toString().replace(".", "")) *
        Number(num2.toString().replace(".", ""))) /
      Math.pow(10, baseNum)
    );
  }

两数相除精度丢失

function numDiv(num1, num2) {
  let baseNum, baseNum1, baseNum2;
  try {
    baseNum1 = num1.toString().split(".")[1].length;
  } catch (e) {
    baseNum1 = 0;
  }
  try {
    baseNum2 = num2.toString().split(".")[1].length;
  } catch (e) {
    baseNum2 = 0;
  }
  baseNum = Math.pow(10, baseNum2 - baseNum1);
  return (
    (Number(num1.toString().replace(".", "")) /
      Number(num2.toString().replace(".", ""))) *
    baseNum
  );
}

保留两位小数

parseFloat(((x * 100) / 100).toFixed(2))

4. 时间格式化:

function timeFormat(time: string, fmt: string) {
  if (!time && time != 0) {
    return ''
  }
  if (
    time.toString().indexOf('-') > 0 &&
    time.toString().indexOf('GMT-') == -1
  ) {
    time = time
      .replace(/T/g, ' ')
      .replace(/\.[\d]{3}Z/, '')
      .replace(/(-)/g, '/') // 将 '-' 替换成 '/'
    if (time.indexOf('.') > -1) {
      time = time.slice(0, time.indexOf('.')) // 删除小数点及后面的数字
    }
  }
  let that = new Date(time)
  let o: any = {
    'M+': that.getMonth() + 1,
    'd+': that.getDate(),
    'h+': that.getHours(),
    'H+': that.getHours(),
    'm+': that.getMinutes(),
    's+': that.getSeconds(),
    'q+': Math.floor((that.getMonth() + 3) / 3),
    S: that.getMilliseconds()
  }
  let week: any = {
    '0': '\u65e5',
    '1': '\u4e00',
    '2': '\u4e8c',
    '3': '\u4e09',
    '4': '\u56db',
    '5': '\u4e94',
    '6': '\u516d'
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (that.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (RegExp.$1.length > 1
        ? RegExp.$1.length > 2
          ? '\u661f\u671f'
          : '\u5468'
        : '') + week[that.getDay() + '']
    )
  }
  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. 业务中常用的正则判断:

税号:

/^[A-Z0-9]{15}$|^[A-Z0-9]{18}$|^[A-Z0-9]{20}$/

电子邮箱:

// 普通
/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
// 带中文
/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/

电话:

// 座机
/^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/
// 手机
/^0?1[3-9][0-9]\d{8}$/

6. 区分IOS/Android:

let isAndroid = navigator.userAgent.indexOf("Android") > -1 || navigator.userAgent.indexOf("Adr") > -1;
      
let isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);

7. 将完整的Base64码转换为Blob:

 function base6toBlob(url: string) {
    let arr = url.split(",");
    let mimeString = arr[0].match(/:(.*?);/)![1];
    let str = atob(arr[1]);
    let u8 = new Uint8Array(str.length);
    for (let i = 0; i < str.length; i++) {
      u8[i] = str.charCodeAt(i);
    }
    return new Blob([u8], { type: mimeString });
  }

8. 将单页PDF以图片的形式展示在页面上

方式一:

这是最简单的处理方式,由后端将获取到的pdf文件处理成图片格式,并将base64编码的图片数据返回给前端; 我们只需要稍加处理用标签展示即可

let pdfimg = "data:image/png;base64," + res.result.picUrlBase64

方式二:

如果后端返回的是base64编码的pdf数据,就需要我们自己手动处理了; 现将base64数据转化成Blob类型,再转化成图片链接用标签展示; 【注意:经过测试,此方法在安卓手机可能会有问题】

 function base6toBlob(url: string) {
    let arr = url.split(",");
    let mimeString = arr[0].match(/:(.*?);/)![1];
    let str = atob(arr[1]);
    let u8 = new Uint8Array(str.length);
    for (let i = 0; i < str.length; i++) {
      u8[i] = str.charCodeAt(i);
    }
    return new Blob([u8], { type: mimeString });
  }
  
// res.result.downloadUrlByt是接口返回的数据
let resultBlob = base6toBlob("data:application/pdf;base64," + res.result.downloadUrlByte);
let pdfimg = window.URL.createObjectURL(resultBlob);

下面的两种方式不可以直接使用返回的流文件,而是需要后端配合将pdf上传到开发服务器上,再将预览地址返回

方式三:

可以使用 iframe / embed 优点:方便快捷,将src设置为指定的pdf链接即可预览; 缺点:样式由浏览器自带的预览工具提供,丑;

方式四:

使用vue-pdf插件,【教程很多不再赘述】 需要注意的是,有些情况下可能出现乱码或部分文字的丢失,可尝试如下方法解决:

// 调用pdf.createLoadingTask方法时传入cMapUrl、cMapPacked
pdf.createLoadingTask({
    url:this.url,
    cMapUrl: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@2.6.347/cmaps/',
    cMapPacked: true
 })

9. 千分位处理

人数千分位

function peopleTothod(num: any) {
  let reg = /\d{1,3}(?=(\d{3})+$)/g;
  return (num + "").replace(reg, "$&,");
}

价钱千分位

function priceTothod(value){
  try {
    if (!value && value !== 0) return "";
    let intPart = Number(value) | 0; //获取整数部分
    let intPartFormat = intPart
      .toString()
      .replace(/(\d)(?=(?:\d{3})+$)/g, "$1,"); //将整数部分逢三一断
    let floatPart = ".00"; //预定义小数部分
    let value2Array = value.toString().split(".");
    //=2表示数据有小数位
    if (value2Array.length == 2) {
      floatPart = value2Array[1].toString(); //拿到小数部分
      if (floatPart.length == 1) {
        //补0,实际上用不着
        return intPartFormat + "." + floatPart + "0";
      } else {
        return intPartFormat + "." + floatPart;
      }
    } else {
      return intPartFormat + floatPart;
    }
  } catch (e) {
    console.log(e);
    return "";
  }
}

priceTothod(Number(金额).toFixed(2));