自定义工具方法

66 阅读3分钟

循环释放对象属性

默认释放所有内部对象属性到最外层,null值默认改为空字符串

function loopExtend(i) {
  let tempRow = {};
  let childObj = {};
  for (const tempRowKey in i) {
    if (
      typeof i[tempRowKey] === "object" &&
      i[tempRowKey] !== null &&
      !Object.prototype.hasOwnProperty.call(i[tempRowKey], "length")
    ) {
      childObj = loopExtend({ ...i[tempRowKey] });
    } else {
      tempRow[tempRowKey] = i[tempRowKey] === null ? "" : i[tempRowKey];
    }
  }
  tempRow = {
    ...tempRow,
    ...childObj
  };
  return tempRow;
}

防双击按钮事件

let switchState;
function loadBtn() {
  // 循环
  let timeOut = null;
  // 触发状态 是否允许触发
  let loading = false;

  // 状态修改 s函数在window下
  switchState = function() {
    loading = !loading;
  }

  // 执行方法
  function shell(fn, wait = 1000){
    // 是否允许触发
    if(!loading) {
      // 修改触发状态为不允许
      switchState();

      timeOut = setTimeout(function(){
        // 执行内容
        fn();
        // 停止循环
        clearTimeout(timeOut)
        // 清除循环
        timeOut = null;
        // 修改触发状态为允许
        switchState();
      }, wait)
    };
  }

  return shell;
}

export default{
    loadBtn: loadBtn()
}
-------
// 使用
loadBtn(() => {...}, 2000)

变量是否为空

function isEmpty(val) {
  // null or undefined
  if (val == null) return true;

  if (typeof val === "boolean") return false;

  if (typeof val === "number") return !val;

  if (val instanceof Error) return val.message === "";

  switch (Object.prototype.toString.call(val)) {
    // String or Array
    case "[object String]":
    case "[object Array]":
      return !val.length;

    // Map or Set or File
    case "[object File]":
    case "[object Map]":
    case "[object Set]": {
      return !val.size;
    }
    // Plain Object
    case "[object Object]": {
      return !Object.keys(val).length;
    }
  }

  return false;
}

判断是否是微信浏览器

function isWeiXin() {
  // #ifdef H5
  // window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息,这个属性可以用来判断浏览器类型
  const ua = window.navigator.userAgent.toLowerCase();
  // 通过正则表达式匹配ua中是否含有MicroMessenger字符串
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    return true;
  }
  return false;
  // #endif
}

从wx浏览器地址栏获取参数

function getQueryString(name) {
  // #ifdef H5
  const obj = {};
  window.location.search.substr(1).split("&").map((i) => {
    obj[i.split("=")[0]] = i.split("=")[1];
    return obj;
  });
  if (obj[name]) {
    return unescape(obj[name]);
  }
  return null;
  // #endif
}

base64转blob

function base64ToBlob(base64) {
  const arr = base64.split(",");
  // 注意base64的最后面中括号和引号是不转译的
  const _arr = arr[1].substring(0, arr[1].length - 2);
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(_arr);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  const blob = new Blob([u8arr], { type: mime });
  const blobUrl = window.URL.createObjectURL(blob);
  return blobUrl;
}

blob转base64

function blobToBase64(blob) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", blob, true);
    xhr.responseType = "blob";
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if ((xhr.status === 200 || xhr.status == 0) && xhr.response) {
          const reader = new FileReader();
          reader.onloadend = function () {
            resolve(reader.result);
          };
          reader.readAsDataURL(xhr.response);
        }
      }
    };
    xhr.send(null);
  });
}

价格前补0

function addZero(num, n) {
    let len = num.toString().length;
    while (len < n) {
            num = '0' + num;
            len++;
    }
    return num;
}

价格验证

function priceReg(price) {
  return /((^[1-9]\d*)|^0)(.\d{0,2}){0,1}$/.test(price);
}

周数字转对应汉字

function numToCN(num) {
    const numArr = ['日', '一', '二', '三', '四', '五', '六'];
    return numArr[num];
}

日期转换

function dateFormat(fmt, date) {
  let ret;
  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;
}

验证身份证

function isId(ID) {
  if (typeof ID !== "string") return false;
  const city = {
    11: "北京",
    12: "天津",
    13: "河北",
    14: "山西",
    15: "内蒙古",
    21: "辽宁",
    22: "吉林",
    23: "黑龙江 ",
    31: "上海",
    32: "江苏",
    33: "浙江",
    34: "安徽",
    35: "福建",
    36: "江西",
    37: "山东",
    41: "河南",
    42: "湖北 ",
    43: "湖南",
    44: "广东",
    45: "广西",
    46: "海南",
    50: "重庆",
    51: "四川",
    52: "贵州",
    53: "云南",
    54: "西藏 ",
    61: "陕西",
    62: "甘肃",
    63: "青海",
    64: "宁夏",
    65: "新疆",
    71: "台湾",
    81: "香港",
    82: "澳门",
    91: "国外"
  };

  const birthday = `${ID.substr(6, 4)}/${Number(ID.substr(10, 2))}/${Number(
    ID.substr(12, 2)
  )}`;
  const d = new Date(birthday);
  const newBirthday = `${d.getFullYear()}/${Number(d.getMonth() + 1)}/${Number(
    d.getDate()
  )}`;
  const currentTime = new Date().getTime();
  const time = d.getTime();
  const arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  const arrCh = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];
  let sum = 0;
  let i;
  let residue;

  if (!/^\d{17}(\d|x)$/i.test(ID)) return false;
  if (city[ID.substr(0, 2)] === undefined) return false;
  if (time >= currentTime || birthday !== newBirthday) return false;
  for (i = 0; i < 17; i++) {
    sum += ID.substr(i, 1) * arrInt[i];
  }
  residue = arrCh[sum % 11];

  return residue === ID.substr(17, 1);
}

验证手机号

function isPhone(phone) {
  const reg = /^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$/;
  return reg.test(phone.replace(/\s/g, ""));
}