实用工具函数.png

1. 数字操作

(1)生成指定范围随机数

  1. export const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

(2)数字千分位分隔

  1. export const format = (n) => {
  2. let num = n.toString();
  3. let decimals = '';
  4. // 是否有小数
  5. num.indexOf('.') > -1 ? decimals = num.split('.')[1] : decimals;
  6. let len = num.length;
  7. if (len <= 3) {
  8. return num;
  9. } else {
  10. let temp = '';
  11. let remainder = len % 3;
  12. decimals ? temp = '.' + decimals : temp;
  13. if (remainder > 0) { // 不是3的整数倍
  14. return num.slice(0, remainder) + ',' + num.slice(remainder, len).match(/\d{3}/g).join(',') + temp;
  15. } else { // 3的整数倍
  16. return num.slice(0, len).match(/\d{3}/g).join(',') + temp;
  17. }
  18. }
  19. }

2. 数组操作

(1)数组乱序

  1. export const arrScrambling = (arr) => {
  2. for (let i = 0; i < arr.length; i++) {
  3. const randomIndex = Math.round(Math.random() * (arr.length - 1 - i)) + i;
  4. [arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]];
  5. }
  6. return arr;
  7. }

(2)数组扁平化

  1. export const flatten = (arr) => {
  2. let result = [];
  3. for(let i = 0; i < arr.length; i++) {
  4. if(Array.isArray(arr[i])) {
  5. result = result.concat(flatten(arr[i]));
  6. } else {
  7. result.push(arr[i]);
  8. }
  9. }
  10. return result;
  11. }

(3)数组中获取随机数

  1. export const sample = arr => arr[Math.floor(Math.random() * arr.length)];

3. 字符串操作

(1)生成随机字符串

  1. export const randomString = (len) => {
  2. let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
  3. let strLen = chars.length;
  4. let randomStr = '';
  5. for (let i = 0; i < len; i++) {
  6. randomStr += chars.charAt(Math.floor(Math.random() * strLen));
  7. }
  8. return randomStr;
  9. };

(2)字符串首字母大写

  1. export const fistLetterUpper = (str) => {
  2. return str.charAt(0).toUpperCase() + str.slice(1);
  3. };

(3)手机号中间四位变成*

  1. export const telFormat = (tel) => {
  2. tel = String(tel);
  3. return tel.substr(0,3) + "****" + tel.substr(7);
  4. };

(4)骆驼命名转换成短横线命名

  1. export const getKebabCase = (str) => {
  2. return str.replace(/[A-Z]/g, (item) => '-' + item.toLowerCase())
  3. }

(5)短横线命名转换成骆驼命名

  1. export const getCamelCase = (str) => {
  2. return str.replace( /-([a-z])/g, (i, item) => item.toUpperCase())
  3. }

(6)全角转换为半角

  1. export const toCDB = (str) => {
  2. let result = "";
  3. for (let i = 0; i < str.length; i++) {
  4. code = str.charCodeAt(i);
  5. if (code >= 65281 && code <= 65374) {
  6. result += String.fromCharCode(str.charCodeAt(i) - 65248);
  7. } else if (code == 12288) {
  8. result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
  9. } else {
  10. result += str.charAt(i);
  11. }
  12. }
  13. return result;
  14. }

(7)半角转换为全角

  1. export const toDBC = (str) => {
  2. let result = "";
  3. for (let i = 0; i < str.length; i++) {
  4. code = str.charCodeAt(i);
  5. if (code >= 33 && code <= 126) {
  6. result += String.fromCharCode(str.charCodeAt(i) + 65248);
  7. } else if (code == 32) {
  8. result += String.fromCharCode(str.charCodeAt(i) + 12288 - 32);
  9. } else {
  10. result += str.charAt(i);
  11. }
  12. }
  13. return result;
  14. }

4. 格式转化

(1)数字转化为大写金额

  1. export const digitUppercase = (n) => {
  2. const fraction = ['角', '分'];
  3. const digit = [
  4. '零', '壹', '贰', '叁', '肆',
  5. '伍', '陆', '柒', '捌', '玖'
  6. ];
  7. const unit = [
  8. ['元', '万', '亿'],
  9. ['', '拾', '佰', '仟']
  10. ];
  11. n = Math.abs(n);
  12. let s = '';
  13. for (let i = 0; i < fraction.length; i++) {
  14. s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
  15. }
  16. s = s || '整';
  17. n = Math.floor(n);
  18. for (let i = 0; i < unit[0].length && n > 0; i++) {
  19. let p = '';
  20. for (let j = 0; j < unit[1].length && n > 0; j++) {
  21. p = digit[n % 10] + unit[1][j] + p;
  22. n = Math.floor(n / 10);
  23. }
  24. s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
  25. }
  26. return s.replace(/(零.)*零元/, '元')
  27. .replace(/(零.)+/g, '零')
  28. .replace(/^整$/, '零元整');
  29. };

(2)数字转化为中文数字

  1. export const intToChinese = (value) => {
  2. const str = String(value);
  3. const len = str.length-1;
  4. const idxs = ['','十','百','千','万','十','百','千','亿','十','百','千','万','十','百','千','亿'];
  5. const num = ['零','一','二','三','四','五','六','七','八','九'];
  6. return str.replace(/([1-9]|0+)/g, ( $, $1, idx, full) => {
  7. let pos = 0;
  8. if($1[0] !== '0'){
  9. pos = len-idx;
  10. if(idx == 0 && $1[0] == 1 && idxs[len-idx] == '十'){
  11. return idxs[len-idx];
  12. }
  13. return num[$1[0]] + idxs[len-idx];
  14. } else {
  15. let left = len - idx;
  16. let right = len - idx + $1.length;
  17. if(Math.floor(right / 4) - Math.floor(left / 4) > 0){
  18. pos = left - left % 4;
  19. }
  20. if( pos ){
  21. return idxs[pos] + num[$1[0]];
  22. } else if( idx + $1.length >= len ){
  23. return '';
  24. }else {
  25. return num[$1[0]]
  26. }
  27. }
  28. });
  29. }

5. 操作存储

(1)存储loalStorage

  1. export const loalStorageSet = (key, value) => {
  2. if (!key) return;
  3. if (typeof value !== 'string') {
  4. value = JSON.stringify(value);
  5. }
  6. window.localStorage.setItem(key, value);
  7. };

(2)获取localStorage

  1. export const loalStorageGet = (key) => {
  2. if (!key) return;
  3. return window.localStorage.getItem(key);
  4. };

(3)删除localStorage

  1. export const loalStorageRemove = (key) => {
  2. if (!key) return;
  3. window.localStorage.removeItem(key);
  4. };

(4)存储sessionStorage

  1. export const sessionStorageSet = (key, value) => {
  2. if (!key) return;
  3. if (typeof value !== 'string') {
  4. value = JSON.stringify(value);
  5. }
  6. window.sessionStorage.setItem(key, value)
  7. };

(5)获取sessionStorage

  1. export const sessionStorageGet = (key) => {
  2. if (!key) return;
  3. return window.sessionStorage.getItem(key)
  4. };

(6)删除sessionStorage

  1. export const sessionStorageRemove = (key) => {
  2. if (!key) return;
  3. window.sessionStorage.removeItem(key)
  4. };

6. 操作cookie

(1)设置cookie

  1. export const setCookie = (key, value, expire) => {
  2. const d = new Date();
  3. d.setDate(d.getDate() + expire);
  4. document.cookie = `${key}=${value};expires=${d.toUTCString()}`
  5. };

(2)读取cookie

  1. export const getCookie = (key) => {
  2. const cookieStr = unescape(document.cookie);
  3. const arr = cookieStr.split('; ');
  4. let cookieValue = '';
  5. for (let i = 0; i < arr.length; i++) {
  6. const temp = arr[i].split('=');
  7. if (temp[0] === key) {
  8. cookieValue = temp[1];
  9. break
  10. }
  11. }
  12. return cookieValue
  13. };

(3)删除cookie

  1. export const delCookie = (key) => {
  2. document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`
  3. };

7. 格式校验

(1)校验身份证号码

  1. export const checkCardNo = (value) => {
  2. let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  3. return reg.test(value);
  4. };

(2)校验是否包含中文

  1. export const haveCNChars => (value) => {
  2. return /[\u4e00-\u9fa5]/.test(value);
  3. }

(3)校验是否为中国大陆的邮政编码

  1. export const isPostCode = (value) => {
  2. return /^[1-9][0-9]{5}$/.test(value.toString());
  3. }

(4)校验是否为IPv6地址

  1. export const isIPv6 = (str) => {
  2. return Boolean(str.match(/:/g)?str.match(/:/g).length<=7:false && /::/.test(str)?/^([\da-f]{1,4}(:|::)){1,6}[\da-f]{1,4}$/i.test(str):/^([\da-f]{1,4}:){7}[\da-f]{1,4}$/i.test(str));
  3. }

(5)校验是否为邮箱地址

  1. export const isEmail = (value) {
  2. return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value);
  3. }

(6)校验是否为中国大陆手机号

  1. export const isTel = (value) => {
  2. return /^1[3,4,5,6,7,8,9][0-9]{9}$/.test(value.toString());
  3. }

(7)校验是否包含emoji表情

  1. export const isEmojiCharacter = (value) => {
  2. value = String(value);
  3. for (let i = 0; i < value.length; i++) {
  4. const hs = value.charCodeAt(i);
  5. if (0xd800 <= hs && hs <= 0xdbff) {
  6. if (value.length > 1) {
  7. const ls = value.charCodeAt(i + 1);
  8. const uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
  9. if (0x1d000 <= uc && uc <= 0x1f77f) {
  10. return true;
  11. }
  12. }
  13. } else if (value.length > 1) {
  14. const ls = value.charCodeAt(i + 1);
  15. if (ls == 0x20e3) {
  16. return true;
  17. }
  18. } else {
  19. if (0x2100 <= hs && hs <= 0x27ff) {
  20. return true;
  21. } else if (0x2B05 <= hs && hs <= 0x2b07) {
  22. return true;
  23. } else if (0x2934 <= hs && hs <= 0x2935) {
  24. return true;
  25. } else if (0x3297 <= hs && hs <= 0x3299) {
  26. return true;
  27. } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030
  28. || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b
  29. || hs == 0x2b50) {
  30. return true;
  31. }
  32. }
  33. }
  34. return false;
  35. }

8. 操作URL

(1)获取URL参数列表

  1. export const GetRequest = () => {
  2. let url = location.search;
  3. const paramsStr = /.+\?(.+)$/.exec(url)[1]; // 将 ? 后面的字符串取出来
  4. const paramsArr = paramsStr.split('&'); // 将字符串以 & 分割后存到数组中
  5. let paramsObj = {};
  6. // 将 params 存到对象中
  7. paramsArr.forEach(param => {
  8. if (/=/.test(param)) { // 处理有 value 的参数
  9. let [key, val] = param.split('='); // 分割 key 和 value
  10. val = decodeURIComponent(val); // 解码
  11. val = /^\d+$/.test(val) ? parseFloat(val) : val; // 判断是否转为数字
  12. if (paramsObj.hasOwnProperty(key)) { // 如果对象有 key,则添加一个值
  13. paramsObj[key] = [].concat(paramsObj[key], val);
  14. } else { // 如果对象没有这个 key,创建 key 并设置值
  15. paramsObj[key] = val;
  16. }
  17. } else { // 处理没有 value 的参数
  18. paramsObj[param] = true;
  19. }
  20. })
  21. return paramsObj;
  22. };

(2)检测URL是否有效

  1. export const getUrlState = (URL) => {
  2. let xmlhttp = new ActiveXObject("microsoft.xmlhttp");
  3. xmlhttp.Open("GET", URL, false);
  4. try {
  5. xmlhttp.Send();
  6. } catch (e) {
  7. } finally {
  8. let result = xmlhttp.responseText;
  9. if (result) {
  10. if (xmlhttp.Status == 200) {
  11. return true;
  12. } else {
  13. return false;
  14. }
  15. } else {
  16. return false;
  17. }
  18. }
  19. }

(3)键值对拼接成URL参数

  1. export const params2Url = (obj) => {
  2. let params = []
  3. for (let key in obj) {
  4. params.push(`${key}=${obj[key]}`);
  5. }
  6. return encodeURIComponent(params.join('&'))
  7. }

(4)修改URL中的参数

  1. export const replaceParamVal => (paramName, replaceWith) {
  2. const oUrl = location.href.toString();
  3. const re = eval('/('+ paramName+'=)([^&]*)/gi');
  4. location.href = oUrl.replace(re,paramName+'='+replaceWith);
  5. return location.href;
  6. }

(5)删除URL中指定参数

  1. export const funcUrlDel = (name) => {
  2. const baseUrl = location.origin + location.pathname + "?";
  3. const query = location.search.substr(1);
  4. if (query.indexOf(name) > -1) {
  5. const obj = {};
  6. const arr = query.split("&");
  7. for (let i = 0; i < arr.length; i++) {
  8. arr[i] = arr[i].split("=");
  9. obj[arr[i][0]] = arr[i][1];
  10. }
  11. delete obj[name];
  12. return baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,/g,"&");
  13. }
  14. }

9. 设备判断

(1)判断是移动还是PC设备

  1. export const isMobile = () => {
  2. if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i))) {
  3. return 'mobile';
  4. }
  5. return 'desktop';
  6. }

(2)判断是否是苹果还是安卓移动设备

  1. export const isAppleMobileDevice = () => {
  2. let reg = /iphone|ipod|ipad|Macintosh/i;
  3. return reg.test(navigator.userAgent.toLowerCase());
  4. }

(3)判断是否是安卓移动设备

  1. export const isAndroidMobileDevice = () => {
  2. return /android/i.test(navigator.userAgent.toLowerCase());
  3. }

(4)判断是Windows还是Mac系统

  1. export const osType = () => {
  2. const agent = navigator.userAgent.toLowerCase();
  3. const isMac = /macintosh|mac os x/i.test(navigator.userAgent);
  4. const isWindows = agent.indexOf("win64") >= 0 || agent.indexOf("wow64") >= 0 || agent.indexOf("win32") >= 0 || agent.indexOf("wow32") >= 0;
  5. if (isWindows) {
  6. return "windows";
  7. }
  8. if(isMac){
  9. return "mac";
  10. }
  11. }

(5)判断是否是微信/QQ内置浏览器

  1. export const broswer = () => {
  2. const ua = navigator.userAgent.toLowerCase();
  3. if (ua.match(/MicroMessenger/i) == "micromessenger") {
  4. return "weixin";
  5. } else if (ua.match(/QQ/i) == "qq") {
  6. return "QQ";
  7. }
  8. return false;
  9. }

(6)浏览器型号和版本

  1. export const getExplorerInfo = () => {
  2. let t = navigator.userAgent.toLowerCase();
  3. return 0 <= t.indexOf("msie") ? { //ie < 11
  4. type: "IE",
  5. version: Number(t.match(/msie ([\d]+)/)[1])
  6. } : !!t.match(/trident\/.+?rv:(([\d.]+))/) ? { // ie 11
  7. type: "IE",
  8. version: 11
  9. } : 0 <= t.indexOf("edge") ? {
  10. type: "Edge",
  11. version: Number(t.match(/edge\/([\d]+)/)[1])
  12. } : 0 <= t.indexOf("firefox") ? {
  13. type: "Firefox",
  14. version: Number(t.match(/firefox\/([\d]+)/)[1])
  15. } : 0 <= t.indexOf("chrome") ? {
  16. type: "Chrome",
  17. version: Number(t.match(/chrome\/([\d]+)/)[1])
  18. } : 0 <= t.indexOf("opera") ? {
  19. type: "Opera",
  20. version: Number(t.match(/opera.([\d]+)/)[1])
  21. } : 0 <= t.indexOf("Safari") ? {
  22. type: "Safari",
  23. version: Number(t.match(/version\/([\d]+)/)[1])
  24. } : {
  25. type: t,
  26. version: -1
  27. }
  28. }

10. 浏览器操作

(1)滚动到页面顶部

  1. export const scrollToTop = () => {
  2. const height = document.documentElement.scrollTop || document.body.scrollTop;
  3. if (height > 0) {
  4. window.requestAnimationFrame(scrollToTop);
  5. window.scrollTo(0, height - height / 8);
  6. }
  7. }

(2)滚动到页面底部

  1. export const scrollToBottom = () => {
  2. window.scrollTo(0, document.documentElement.clientHeight);
  3. }

(3)滚动到指定元素区域

  1. export const smoothScroll = (element) => {
  2. document.querySelector(element).scrollIntoView({
  3. behavior: 'smooth'
  4. });
  5. };

(4)获取可视窗口高度

  1. export const getClientHeight = () => {
  2. let clientHeight = 0;
  3. if (document.body.clientHeight && document.documentElement.clientHeight) {
  4. clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
  5. }
  6. else {
  7. clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
  8. }
  9. return clientHeight;
  10. }

(5)获取可视窗口宽度

  1. export const getPageViewWidth = () => {
  2. return (document.compatMode == "BackCompat" ? document.body : document.documentElement).clientWidth;
  3. }

(6)打开浏览器全屏

  1. export const toFullScreen = () => {
  2. let element = document.body;
  3. if (element.requestFullscreen) {
  4. element.requestFullscreen()
  5. } else if (element.mozRequestFullScreen) {
  6. element.mozRequestFullScreen()
  7. } else if (element.msRequestFullscreen) {
  8. element.msRequestFullscreen()
  9. } else if (element.webkitRequestFullscreen) {
  10. element.webkitRequestFullScreen()
  11. }
  12. }

(7)退出浏览器全屏

  1. export const exitFullscreen = () => {
  2. if (document.exitFullscreen) {
  3. document.exitFullscreen()
  4. } else if (document.msExitFullscreen) {
  5. document.msExitFullscreen()
  6. } else if (document.mozCancelFullScreen) {
  7. document.mozCancelFullScreen()
  8. } else if (document.webkitExitFullscreen) {
  9. document.webkitExitFullscreen()
  10. }
  11. }

11. 时间操作

(1)当前时间

  1. export const nowTime = () => {
  2. const now = new Date();
  3. const year = now.getFullYear();
  4. const month = now.getMonth();
  5. const date = now.getDate() >= 10 ? now.getDate() : ('0' + now.getDate());
  6. const hour = now.getHours() >= 10 ? now.getHours() : ('0' + now.getHours());
  7. const miu = now.getMinutes() >= 10 ? now.getMinutes() : ('0' + now.getMinutes());
  8. const sec = now.getSeconds() >= 10 ? now.getSeconds() : ('0' + now.getSeconds());
  9. return +year + "年" + (month + 1) + "月" + date + "日 " + hour + ":" + miu + ":" + sec;
  10. }

(2)格式化时间

  1. export const dateFormater = (formater, time) => {
  2. let date = time ? new Date(time) : new Date(),
  3. Y = date.getFullYear() + '',
  4. M = date.getMonth() + 1,
  5. D = date.getDate(),
  6. H = date.getHours(),
  7. m = date.getMinutes(),
  8. s = date.getSeconds();
  9. return formater.replace(/YYYY|yyyy/g, Y)
  10. .replace(/YY|yy/g, Y.substr(2, 2))
  11. .replace(/MM/g,(M<10 ? '0' : '') + M)
  12. .replace(/DD/g,(D<10 ? '0' : '') + D)
  13. .replace(/HH|hh/g,(H<10 ? '0' : '') + H)
  14. .replace(/mm/g,(m<10 ? '0' : '') + m)
  15. .replace(/ss/g,(s<10 ? '0' : '') + s)
  16. }
  17. // dateFormater('YYYY-MM-DD HH:mm:ss')
  18. // dateFormater('YYYYMMDDHHmmss')

12. JavaScript操作

(1)阻止冒泡事件

  1. export const stopPropagation = (e) => {
  2. e = e || window.event;
  3. if(e.stopPropagation) { // W3C阻止冒泡方法
  4. e.stopPropagation();
  5. } else {
  6. e.cancelBubble = true; // IE阻止冒泡方法
  7. }
  8. }

(2)防抖函数

  1. export const debounce = (fn, wait) => {
  2. let timer = null;
  3. return function() {
  4. let context = this,
  5. args = arguments;
  6. if (timer) {
  7. clearTimeout(timer);
  8. timer = null;
  9. }
  10. timer = setTimeout(() => {
  11. fn.apply(context, args);
  12. }, wait);
  13. };
  14. }

(3)节流函数

  1. export const throttle = (fn, delay) => {
  2. let curTime = Date.now();
  3. return function() {
  4. let context = this,
  5. args = arguments,
  6. nowTime = Date.now();
  7. if (nowTime - curTime >= delay) {
  8. curTime = Date.now();
  9. return fn.apply(context, args);
  10. }
  11. };
  12. }

(4)数据类型判断

  1. export const getType = (value) => {
  2. if (value === null) {
  3. return value + "";
  4. }
  5. // 判断数据是引用类型的情况
  6. if (typeof value === "object") {
  7. let valueClass = Object.prototype.toString.call(value),
  8. type = valueClass.split(" ")[1].split("");
  9. type.pop();
  10. return type.join("").toLowerCase();
  11. } else {
  12. // 判断数据是基本数据类型的情况和函数的情况
  13. return typeof value;
  14. }
  15. }

(5)对象深拷贝

  1. export const deepClone = (obj, hash = new WeakMap() => {
  2. // 日期对象直接返回一个新的日期对象
  3. if (obj instanceof Date){
  4. return new Date(obj);
  5. }
  6. //正则对象直接返回一个新的正则对象
  7. if (obj instanceof RegExp){
  8. return new RegExp(obj);
  9. }
  10. //如果循环引用,就用 weakMap 来解决
  11. if (hash.has(obj)){
  12. return hash.get(obj);
  13. }
  14. // 获取对象所有自身属性的描述
  15. let allDesc = Object.getOwnPropertyDescriptors(obj);
  16. // 遍历传入参数所有键的特性
  17. let cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc)
  18. hash.set(obj, cloneObj)
  19. for (let key of Reflect.ownKeys(obj)) {
  20. if(typeof obj[key] === 'object' && obj[key] !== null){
  21. cloneObj[key] = deepClone(obj[key], hash);
  22. } else {
  23. cloneObj[key] = obj[key];
  24. }
  25. }
  26. return cloneObj
  27. }