当前位置:主页 > 网页前端 > JavaScript代码 >

18个高频使用的JS工具方法总结

时间:2023-01-13 11:04:03 | 栏目:JavaScript代码 | 点击:

前言

将自己做前端6年以来在项目中使用很高频的工具方法整理了出来,分享一下,虽然现在有很多工具类也提供了这些方法,封装的也更为完善,简单的调用一下就可以使用,但是我还是分享出来了。是希望能够知其然也知其所以然,不要只会调用 api,也要会写 api。

1. 回到顶部

较为平滑的回到顶部方案

const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};
scrollToTop();

2. 删除数组指定项

项目中经常会使用的工具方法,传入目标数组和目标元素,返回一个新数组。

const removeArray = (arr, item) => {
  let result = [];
  let index = -1;
  if (!(arr != null && arr.length)) {
    return result;
  }
  result = arr;
  if (Object.prototype.toString.call(item) == "[object Object]") {
    index = arr.findIndex((i) => isEqualObject(i, item));
  } else {
    index = arr.findIndex((i) => i === item);
  }
  if (index > -1) result.splice(index, 1);
  return result;
};

const isEqualObject = (obja, objb) => {
  const aProps = Object.getOwnPropertyNames(obja);
  const bProps = Object.getOwnPropertyNames(objb);
  if (aProps.length != bProps.length) {
    return false;
  }
  for (let i = 0; i < aProps.length; i++) {
    let propName = aProps[i];
    let propA = obja[propName];
    let propB = objb[propName];
    if (!objb.hasOwnProperty(propName)) return false;
    if (propA instanceof Object) {
      if (!this.isEqualObject(propA, propB)) {
        return false;
      }
    } else if (propA !== propB) {
      return false;
    }
  }
  return true;
};

removeArray([{ name: 1 }, { name: "1" }, 1, "1"], { name: "1" });

3. 获取 url 某一个参数

用于获取url传参获取参数

const getUrlParam = (key) => {
  const url = new URL(window.location.href);
  const value = url.searchParams.get(key);
  return value;
};
getUrlParam("id");

4. 复制文本

复制各种自定义的文本,浏览器兼容性高

const copyText = (text) => {
  const clipboardData = window.clipboardData;
  if (clipboardData) {
    clipboardData.clearData();
    clipboardData.setData("Text", text);
    return true;
  } else if (document.execCommand) {
    const el = document.createElement("textarea");
    el.value = text;
    el.setAttribute("readonly", "");
    el.style.position = "absolute";
    el.style.left = "-9999px";
    document.body.appendChild(el);
    el.select();
    document.execCommand("copy");
    document.body.removeChild(el);
    return true;
  }
  return false;
};
copyText("Test");

5. 禁止复制文本

body {
  user-select: none;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
}
// 禁止右键菜单
document.body.oncontextmenu = (e) => {
  return false;
};
// 禁止选中文字
document.body.onselectstart = (e) => {
  return false;
};
// 禁止复制
document.body.oncopy = (e) => {
  return false;
};
// 禁止剪切
document.body.oncut = (e) => {
  return false;
};
// 禁止粘贴
document.body.onpaste = (e) => {
  return false;
};

6. 复制文本带版权信息

document.body.oncopy = (event) => {
  event.preventDefault();
  const clipboardData = event.clipboardData;
  let text = window.getSelection(0).toString();
  text = `${text}\n这是插入的文本\n 作者:于五五\n`;
  if (clipboardData) {
    clipboardData.clearData();
    clipboardData.setData("Text", text);
    return true;
  } else if (document.execCommand) {
    window.clipboardData.setData("Text", text);
  }
  return false;
};

7. 判断数据类型和数据值

很常用的工具类,用于校验数据是否合法

// 是否是字符串
function isString(obj) {
  return Object.prototype.toString.call(obj) == "[object String]";
}

// 是否是数字
function isNumber(obj) {
  return (
    Object.prototype.toString.call(obj) == "[object Number]" &&
    /[\d\.]+/.test(String(obj))
  );
}

// 是否是布尔
function isBoolean(obj) {
  return Object.prototype.toString.call(obj) == "[object Boolean]";
}

// 是否是数组
function isArray(obj) {
  return Object.prototype.toString.call(obj) === "[object Array]";
}

// 是否是对象
function isObject(arg) {
  if (arg == null) {
    return false;
  } else {
    return Object.prototype.toString.call(arg) == "[object Object]";
  }
}

// 是否是方法
function isFunction(arg) {
  const type = Object.prototype.toString.call(arg);
  return type == "[object Function]" || type == "[object AsyncFunction]";
}

// 是否是时间格式
function isDate(obj) {
  return Object.prototype.toString.call(obj) == "[object Date]";
}

// 是否是时间undefined
function isUndefined(arg) {
  return arg === void 0;
}

// 是否是空对象
function isEmptyObject(arg) {
  if (isObject(arg)) {
    for (var key in arg) {
      if (Object.prototype.hasOwnProperty.call(arg, key)) {
        return false;
      }
    }
    return true;
  }
  return false;
}

8. ua 环境判断

用来区分不同平台,常用在ios端做适配

const getUaInfo = () => {
  const ua = navigator.userAgent.toLowerCase();
  const Agents = [
    "Android",
    "android",
    "iPhone",
    "SymbianOS",
    "Windows Phone",
    "iPad",
    "iPod",
  ];
  let isPc = true;
  for (var i = 0; i < Agents.length; i++) {
    if (userAgentInfo.includes(Agents[i])) {
      isPc = false;
      break;
    }
  }
  return {
    // 是不是ios
    isIos:
      !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) || ua.includes("mac os x"),
    // 是不是安卓
    isAndroid:
      ua.includes("android") || ua.includes("Android") || ua.includes("Adr"),
    // 是不是微信环境
    isWeixin: ua.match(/MicroMessenger/i) == "micromessenger",
    // 是不是电脑端
    isPc: isPc,
  };
};

9. 时间格式转换

// Date转yyyy-MM-dd HH:mm:ss
const filterTimeByDate = (date, pattern = "yyyy-MM-dd HH:mm:ss") => {
  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(pattern)) {
    pattern = pattern.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(pattern)) {
      pattern = pattern.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return pattern;
};
filterTimeByDate(new Date());

// 时间戳转yyyy-MM-dd HH:mm:ss
const timestampToTime = (timestamp) => {
  const date = new Date(
    String(timestamp).length > 10 ? timestamp : timestamp * 1000
  ); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
  const Y = date.getFullYear() + "-";
  const M =
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
  const D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
  const h =
    (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  const m =
    (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
    ":";
  const s =
    date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return Y + M + D + h + m + s;
};
timestampToTime(new Date().getTime());

// yyyy-MM-dd HH:mm:ss转时间戳
const timeToTimestamp = (time, isMilli = true) => {
  const timestamp = new Date(time).getTime(); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
  return isMilli ? timestamp : timestamp / 1000;
};
timeToTimestamp("2022-04-26 10:11:11");

10. 函数防抖

const debounce = (fn, delay) => {
  let timer = null;
  return function (e) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, arguments);
    }, delay);
  };
};
document.addEventListener(
  "scroll",
  debounce(function () {
    console.log("执行");
  }, 2000)
);

11. 全屏/退出全屏

function toFullScreen() {
  let = document.documentElement;
  el.webkitRequestFullScreen
    ? el.webkitRequestFullScreen()
    : el.mozRequestFullScreen
    ? el.mozRequestFullScreen()
    : el.msRequestFullscreen
    ? el.msRequestFullscreen()
    : el.requestFullScreen
    ? el.requestFullScreen()
    : alert("当前浏览器不支持该功能");
}

function exitFullscreen() {
  let el = document;
  el.webkitCancelFullScreen
    ? el.webkitCancelFullScreen()
    : el.mozCancelFullScreen
    ? el.mozCancelFullScreen()
    : el.cancelFullScreen
    ? el.cancelFullScreen()
    : el.msExitFullscreen
    ? el.msExitFullscreen()
    : el.exitFullscreen
    ? el.exitFullscreen()
    : alert("当前浏览器不支持该功能");
}

12. 禁止打开控制台调试

用来防止部分用户通过源码攻击服务器,增加破解难度

setInterval(function () {
  check();
}, 4000);
const check = () => {
  function doCheck(a) {
    if (("" + a / a)["length"] !== 1 || a % 20 === 0) {
      (function () {}["constructor"]("debugger")());
    } else {
      (function () {}["constructor"]("debugger")());
    }
    doCheck(++a);
  }
  try {
    doCheck(0);
  } catch (err) {}
};
check();

13. 密码强度展示

const checkPwd = (str) => {
  let Lv = 0;
  if (str.length < 6) {
    return Lv;
  }
  if (/[0-9]/.test(str)) {
    Lv++;
  }
  if (/[a-z]/.test(str)) {
    Lv++;
  }
  if (/[A-Z]/.test(str)) {
    Lv++;
  }
  if (/[\.|-|_]/.test(str)) {
    Lv++;
  }
  return Lv;
};

14. 五星好评

const getRate = (rate = 0) => {
  return "★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);
};
getRate(3);

15. 保留 n 位小数

const filterToFixed => (num, n = 2) {
    return parseFloat(num.toFixed(n), 10);
}

16. 金额转大写

商城项目里订单模块很常用的工具方法

const convertCurrency = (money) => {
  //汉字的数字
  const cnNums = new Array(
    "零",
    "壹",
    "贰",
    "叁",
    "肆",
    "伍",
    "陆",
    "柒",
    "捌",
    "玖"
  );
  //基本单位
  const cnIntRadice = new Array("", "拾", "佰", "仟");
  //对应整数部分扩展单位
  const cnIntUnits = new Array("", "万", "亿", "兆");
  //对应小数部分单位
  const cnDecUnits = new Array("角", "分", "毫", "厘");
  //整数金额时后面跟的字符
  const cnInteger = "整";
  //整型完以后的单位
  const cnIntLast = "元";
  //最大处理的数字
  const maxNum = 999999999999999.9999;
  //金额整数部分
  let integerNum;
  //金额小数部分
  let decimalNum;
  //输出的中文金额字符串
  let chineseStr = "";
  //分离金额后用的数组,预定义
  let parts;
  // 传入的参数为空情况
  if (money == "") {
    return "";
  }
  money = parseFloat(money);
  if (money >= maxNum) {
    return "";
  }
  // 传入的参数为0情况
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger;
    return chineseStr;
  }
  // 转为字符串
  money = money.toString();
  // indexOf 检测某字符在字符串中首次出现的位置 返回索引值(从0 开始) -1 代表无
  if (money.indexOf(".") == -1) {
    integerNum = money;
    decimalNum = "";
  } else {
    parts = money.split(".");
    integerNum = parts[0];
    decimalNum = parts[1].substr(0, 4);
  }
  //转换整数部分
  if (parseInt(integerNum, 10) > 0) {
    let zeroCount = 0;
    let IntLen = integerNum.length;
    for (let i = 0; i < IntLen; i++) {
      let n = integerNum.substr(i, 1);
      let p = IntLen - i - 1;
      let q = p / 4;
      let m = p % 4;
      if (n == "0") {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        zeroCount = 0;
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    // 最后+ 元
    chineseStr += cnIntLast;
  }
  // 转换小数部分
  if (decimalNum != "") {
    let decLen = decimalNum.length;
    for (let i = 0; i < decLen; i++) {
      let n = decimalNum.substr(i, 1);
      if (n != "0") {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (chineseStr == "") {
    chineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (decimalNum == "") {
    chineseStr += cnInteger;
  }

  return chineseStr;
};

17. 常用正则判断

// 校验昵称为2-9位中文
const validateName = (name) => {
  const reg = /^[\u4e00-\u9fa5]{2,9}$/;
  return reg.test(name);
};

// 校验手机号
const validateMobile = (mobile) => {
  const reg = /^1[3,4,5,6,7,8,9]\d{9}$/;
  return reg.test(mobile);
};

// 校验6到18位大小写字母数字下划线组成的密码
const validatePassword = (password) => {
  const reg = /^[a-zA-Z0-9_]{6,18}$/;
  return reg.test(password);
};

// 校验身份证号
const validateCardId = (cardId) => {
  const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  return reg.test(cardId);
};

18. 解决运算精度丢失的问题

用来解决前端计算金额时精度丢失的问题

const calculation = {
  // 加法
  plus(arg1, arg2) {
    var r1, r2, m;
    try {
      r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m;
  },
  //减法
  subtract(arg1, arg2) {
    var r1, r2, m, n;
    try {
      r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    n = r1 >= r2 ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
  },
  //   乘法
  multiply(arg1, arg2) {
    var m = 0,
      s1 = arg1.toString(),
      s2 = arg2.toString();
    try {
      m += s1.split(".")[1].length;
    } catch (e) {}
    try {
      m += s2.split(".")[1].length;
    } catch (e) {}
    return (
      (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
      Math.pow(10, m)
    );
  },
  //   除法
  divide(arg1, arg2) {
    var t1 = 0,
      t2 = 0,
      r1,
      r2;
    try {
      t1 = arg1.toString().split(".")[1].length;
    } catch (e) {}
    try {
      t2 = arg2.toString().split(".")[1].length;
    } catch (e) {}
    r1 = Number(arg1.toString().replace(".", ""));
    r2 = Number(arg2.toString().replace(".", ""));
    return (r1 / r2) * Math.pow(10, t2 - t1);
  },
};

您可能感兴趣的文章:

相关文章