Skip to content

表单验证

是否为空

JavaScript
  isNullOrEmpty: function(value) {
    //是否为空
    return (value === null || value === '' || value === undefined) ? true : false;
  }
  isNullOrEmpty: function(value) {
    //是否为空
    return (value === null || value === '' || value === undefined) ? true : false;
  }

去空格

JavaScript
  trim: function(value) {
    //去空格
    return value.replace(/(^\s*)|(\s*$)/g, "");
  }
  trim: function(value) {
    //去空格
    return value.replace(/(^\s*)|(\s*$)/g, "");
  }

是否为手机号

JavaScript
  isMobile: function(value) {
    // const reg = /^1[0-9]{10,10}$/
    //是否为手机号
    return /^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(value);
  }
  isMobile: function(value) {
    // const reg = /^1[0-9]{10,10}$/
    //是否为手机号
    return /^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(value);
  }

金额保留两位小数

JavaScript
  isFloat: function(value) {
    //金额,只允许保留两位小数
    return /^([0-9]*[.]?[0-9])[0-9]{0,1}$/.test(value);
  }
  isFloat: function(value) {
    //金额,只允许保留两位小数
    return /^([0-9]*[.]?[0-9])[0-9]{0,1}$/.test(value);
  }

是否全为数字

JavaScript
  isNum: function(value) {
    //是否全为数字
    return /^[0-9]+$/.test(value);
  }
  isNum: function(value) {
    //是否全为数字
    return /^[0-9]+$/.test(value);
  }

密码检测

JavaScript
  checkPwd: function(value) {
    //密码为8~20位数字和字母组合
    return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/.test(value);
  }
  checkPwd: function(value) {
    //密码为8~20位数字和字母组合
    return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/.test(value);
  }

密码是否在 6-24 之间

JavaScript
  is6To24Pwd: function(value) {
    return value && value.length >= 6 && value.length <= 24
  }
  is6To24Pwd: function(value) {
    return value && value.length >= 6 && value.length <= 24
  }

是否为 URL

JavaScript
  checkUrl: function(url) {
    return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
  }
  checkUrl: function(url) {
    return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
  }

格式化手机号码

JavaScript
  formatNum: function(num) {
    //格式化手机号码
    if (utils.isMobile(num)) {
      num = num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
    }
    return num;
  }
  formatNum: function(num) {
    //格式化手机号码
    if (utils.isMobile(num)) {
      num = num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
    }
    return num;
  }

验证正整数(包含0)

JavaScript
function  CheckPositiveInteger (rule, value, callback){
    let reg = /^[1-9]\d*$/g;
    // console.log(value)
    if (!reg.test(value) && value !== '') {
      callback(new Error('请输入正整数'));
    } else {
      callback();
    }
  }
function  CheckPositiveInteger (rule, value, callback){
    let reg = /^[1-9]\d*$/g;
    // console.log(value)
    if (!reg.test(value) && value !== '') {
      callback(new Error('请输入正整数'));
    } else {
      callback();
    }
  }

验证邮箱

JavaScript
function  CheckEmail (rule, value, callback){
     let reg = /^[A-z0-9_]{3,12}@[A-z0-9]{2,12}(\.com|\.cn|\.com\.cn)$/g;
    if (!reg.test(value) && value !== '') {
      callback('邮箱格式不正确');
    } else {
      callback();
    }
  }
function  CheckEmail (rule, value, callback){
     let reg = /^[A-z0-9_]{3,12}@[A-z0-9]{2,12}(\.com|\.cn|\.com\.cn)$/g;
    if (!reg.test(value) && value !== '') {
      callback('邮箱格式不正确');
    } else {
      callback();
    }
  }

验证价格

JavaScript
function CheckPrice (rule, value, callback)  {
    if (!value && value !== 0) {
      return callback(new Error('该项为必填项'));
    } else if (!parseFloat(value) && parseFloat(value) != 0) {
      return callback(new Error('请输入阿拉伯数字'));
    } else if (value < 0) {
      return callback(new Error('请输入正确的价格'));
    } else {
      callback();
    }
  }
function CheckPrice (rule, value, callback)  {
    if (!value && value !== 0) {
      return callback(new Error('该项为必填项'));
    } else if (!parseFloat(value) && parseFloat(value) != 0) {
      return callback(new Error('请输入阿拉伯数字'));
    } else if (value < 0) {
      return callback(new Error('请输入正确的价格'));
    } else {
      callback();
    }
  }

验证IP地址

JavaScript
function CheckIp (rule, value, callback)  {
    let reg =
      /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
    if (!reg.test(value) && value !== '') {
      callback(new Error('输入正确IP地址'));
    } else {
      callback();
    }
  }
function CheckIp (rule, value, callback)  {
    let reg =
      /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
    if (!reg.test(value) && value !== '') {
      callback(new Error('输入正确IP地址'));
    } else {
      callback();
    }
  }

验证域名网址

JavaScript
function CheckWebsite (rule, value, callback) {
    let reg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
    if (!reg.test(value) && value !== '') {
      callback(new Error('请输入正确的网址'));
    } else {
      callback();
    }
  }
function CheckWebsite (rule, value, callback) {
    let reg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
    if (!reg.test(value) && value !== '') {
      callback(new Error('请输入正确的网址'));
    } else {
      callback();
    }
  }

常用函数

JS 类型判断

JavaScript
function _typeof(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}
function _typeof(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}

是否是 src

JavaScript
function isSrc(url) {
  return url.indexOf('http') === 0 || url.indexOf('data:image') === 0 || url.indexOf('//') === 0;
}
function isSrc(url) {
  return url.indexOf('http') === 0 || url.indexOf('data:image') === 0 || url.indexOf('//') === 0;
}

是否不是空数组

JavaScript
function isNonEmptyArray(obj = []) {
  return obj && obj.length > 0 && Array.isArray(obj) && typeof obj !== 'undefined';
}
function isNonEmptyArray(obj = []) {
  return obj && obj.length > 0 && Array.isArray(obj) && typeof obj !== 'undefined';
}

是否空对象

JavaScript
function isEmptyObject(obj) {
  return Object.keys(obj).length === 0 && obj.constructor === Object;
}
function isEmptyObject(obj) {
  return Object.keys(obj).length === 0 && obj.constructor === Object;
}

数组去重

JavaScript
function derepeatArray(arr=[], key=null) {
  if (key) {
    const obj = {}
    return arr.reduce((cur,next) => {
        obj[next[key]] ? "" : obj[next[key]] = true && cur.push(next)
        return cur
    },[])
  } else {
    return [...(new Set(arr))]
  }
}
function derepeatArray(arr=[], key=null) {
  if (key) {
    const obj = {}
    return arr.reduce((cur,next) => {
        obj[next[key]] ? "" : obj[next[key]] = true && cur.push(next)
        return cur
    },[])
  } else {
    return [...(new Set(arr))]
  }
}

对象合并

JavaScript
function mergeDeep(target, ...sources) {
  if (!sources.length) return target;
  const source = sources.shift();
  if (isObject(target) && isObject(source)) {
    for (const key in source) {
      if (isObject(source[key])) {
        if (!target[key]) {
          Object.assign(target, {[key]: {}});
        }
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, {[key]: source[key]});
      }
    }
  }
  return mergeDeep(target, ...sources);
}
function mergeDeep(target, ...sources) {
  if (!sources.length) return target;
  const source = sources.shift();
  if (isObject(target) && isObject(source)) {
    for (const key in source) {
      if (isObject(source[key])) {
        if (!target[key]) {
          Object.assign(target, {[key]: {}});
        }
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, {[key]: source[key]});
      }
    }
  }
  return mergeDeep(target, ...sources);
}

扁平化树转树型结构

JavaScript
// 扁平化树转树型结构
export const arrToTree = (list, options = {}) => {
    const { idKey = 'id', parentIdKey = 'parentId' } = options
    let map = {}
    let result = []

    if (!Array.isArray(list)) {
        return []
    }

    list.forEach(item => {
        map[item[idKey]] = item
    })

    list.forEach(item => {
        let parent = map[item[parentIdKey]]
        if (parent) {
            (parent.children || (parent.children = [])).push(item)
        } else {
            result.push(item)
        }
    })

    return result
}
// 扁平化树转树型结构
export const arrToTree = (list, options = {}) => {
    const { idKey = 'id', parentIdKey = 'parentId' } = options
    let map = {}
    let result = []

    if (!Array.isArray(list)) {
        return []
    }

    list.forEach(item => {
        map[item[idKey]] = item
    })

    list.forEach(item => {
        let parent = map[item[parentIdKey]]
        if (parent) {
            (parent.children || (parent.children = [])).push(item)
        } else {
            result.push(item)
        }
    })

    return result
}

树形数据扁平化

JavaScript
function flattenTree(tree) {
  const result = [];

  function traverse(node) {
    result.push(node);
    if (node.children) {
      node.children.forEach(traverse);
      delete node.children;
    }
  }

  tree.forEach(traverse);
  return result;
}
function flattenTree(tree) {
  const result = [];

  function traverse(node) {
    result.push(node);
    if (node.children) {
      node.children.forEach(traverse);
      delete node.children;
    }
  }

  tree.forEach(traverse);
  return result;
}

原生方式生成 UUID

JavaScript
// 原生方式生成UUID
function uuid (length=36) {
    return URL.createObjectURL(new Blob()).substr(length)
}
// 原生方式生成UUID
function uuid (length=36) {
    return URL.createObjectURL(new Blob()).substr(length)
}

判断文件上传类型

JavaScript
/**
 * @param: fileName - 文件名称
 * @param: 数据返回 1) 无后缀匹配 - false
 * @param: 数据返回 2) 匹配图片 - image
 * @param: 数据返回 3) 匹配 txt - txt
 * @param: 数据返回 4) 匹配 excel - excel
 * @param: 数据返回 5) 匹配 word - word
 * @param: 数据返回 6) 匹配 pdf - pdf
 * @param: 数据返回 7) 匹配 ppt - ppt
 * @param: 数据返回 8) 匹配 视频 - video
 * @param: 数据返回 9) 匹配 音频 - radio
 * @param: 数据返回 10) 其他匹配项 - other
 * @author: ljw
 **/
export function fileSuffixTypeUtil (fileName) {
  // 后缀获取
  let suffix = ''
  // 获取类型结果
  let result = ''
  try {
    const flieArr = fileName.split('.')
    suffix = flieArr[flieArr.length - 1]
  } catch (err) {
    suffix = ''
  }
  // fileName无后缀返回 false
  if (!suffix) {
    result = false
    return result
  }
  // 图片格式
  const imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif']
  // 进行图片匹配
  result = imglist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'image'
    return result
  }

  // 匹配txt
  const txtlist = ['txt']
  result = txtlist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'txt'
    return result
  }

  // 匹配 excel
  const excelist = ['xls', 'xlsx']
  result = excelist.some(function (item) {
    return item == suffix
  })

  if (result) {
    result = 'excel'
    return result
  }

  // 匹配 word
  const wordlist = ['doc', 'docx']
  result = wordlist.some(function (item) {
    return item == suffix
  })

  if (result) {
    result = 'word'
    return result
  }

  // 匹配 pdf
  const pdflist = ['pdf']
  result = pdflist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'pdf'
    return result
  }

  // 匹配 ppt
  const pptlist = ['ppt']
  result = pptlist.some(function (item) {
    return item == suffix
  })

  if (result) {
    result = 'ppt'
    return result
  }

  // 匹配 视频

  const videolist = ['mp4', 'm2v', 'mkv']
  result = videolist.some(function (item) {
    return item == suffix
  })

  if (result) {
    result = 'video'
    return result
  }

  // 匹配 音频
  const radiolist = ['mp3', 'wav', 'wmv']
  result = radiolist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'radio'
    return result
  }

  // 其他 文件类型
  result = 'other'
  return result
}
/**
 * @param: fileName - 文件名称
 * @param: 数据返回 1) 无后缀匹配 - false
 * @param: 数据返回 2) 匹配图片 - image
 * @param: 数据返回 3) 匹配 txt - txt
 * @param: 数据返回 4) 匹配 excel - excel
 * @param: 数据返回 5) 匹配 word - word
 * @param: 数据返回 6) 匹配 pdf - pdf
 * @param: 数据返回 7) 匹配 ppt - ppt
 * @param: 数据返回 8) 匹配 视频 - video
 * @param: 数据返回 9) 匹配 音频 - radio
 * @param: 数据返回 10) 其他匹配项 - other
 * @author: ljw
 **/
export function fileSuffixTypeUtil (fileName) {
  // 后缀获取
  let suffix = ''
  // 获取类型结果
  let result = ''
  try {
    const flieArr = fileName.split('.')
    suffix = flieArr[flieArr.length - 1]
  } catch (err) {
    suffix = ''
  }
  // fileName无后缀返回 false
  if (!suffix) {
    result = false
    return result
  }
  // 图片格式
  const imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif']
  // 进行图片匹配
  result = imglist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'image'
    return result
  }

  // 匹配txt
  const txtlist = ['txt']
  result = txtlist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'txt'
    return result
  }

  // 匹配 excel
  const excelist = ['xls', 'xlsx']
  result = excelist.some(function (item) {
    return item == suffix
  })

  if (result) {
    result = 'excel'
    return result
  }

  // 匹配 word
  const wordlist = ['doc', 'docx']
  result = wordlist.some(function (item) {
    return item == suffix
  })

  if (result) {
    result = 'word'
    return result
  }

  // 匹配 pdf
  const pdflist = ['pdf']
  result = pdflist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'pdf'
    return result
  }

  // 匹配 ppt
  const pptlist = ['ppt']
  result = pptlist.some(function (item) {
    return item == suffix
  })

  if (result) {
    result = 'ppt'
    return result
  }

  // 匹配 视频

  const videolist = ['mp4', 'm2v', 'mkv']
  result = videolist.some(function (item) {
    return item == suffix
  })

  if (result) {
    result = 'video'
    return result
  }

  // 匹配 音频
  const radiolist = ['mp3', 'wav', 'wmv']
  result = radiolist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'radio'
    return result
  }

  // 其他 文件类型
  result = 'other'
  return result
}

文件下载

JavaScript
/**
 * @param: fileType - 文件类型
 * @param: fileName - 文件名称
 * @param: data  - 数据流文件
 **/

export function download (fileType, fileName, data) {
  let downType = ''
  let downName = ''
  if (fileType === 'image') {
    downType = 'image/png'
    downName = fileName + '.png'
  } else if (fileType === 'word') {
    downType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    downName = fileName + '.docx'
  } else if (fileType === 'video') {
    downType = 'video/mpeg4'
    downName = fileName + '.mp4'
  } else if (fileType === 'radio') {
    downType = 'audio/mpeg'
    downName = fileName + '.mp3'
  } else if (fileType === 'pdf') {
    downType = 'application/pdf'
    downName = fileName + '.pdf'
  }

  const blob = new Blob([data], { type: downType })
  const downloadElement = document.createElement('a')
  const href = window.URL.createObjectURL(blob)
  downloadElement.href = href
  document.body.appendChild(downloadElement)
  // downloadElement.setAttribute("download", downName);//设置下载名称
  downloadElement.download = downName // 设置下载文件名称
  downloadElement.click()
  document.body.removeChild(downloadElement) // 移除元素;防止连续点击创建多个a标签
  window.URL.revokeObjectURL(href)
}
/**
 * @param: fileType - 文件类型
 * @param: fileName - 文件名称
 * @param: data  - 数据流文件
 **/

export function download (fileType, fileName, data) {
  let downType = ''
  let downName = ''
  if (fileType === 'image') {
    downType = 'image/png'
    downName = fileName + '.png'
  } else if (fileType === 'word') {
    downType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    downName = fileName + '.docx'
  } else if (fileType === 'video') {
    downType = 'video/mpeg4'
    downName = fileName + '.mp4'
  } else if (fileType === 'radio') {
    downType = 'audio/mpeg'
    downName = fileName + '.mp3'
  } else if (fileType === 'pdf') {
    downType = 'application/pdf'
    downName = fileName + '.pdf'
  }

  const blob = new Blob([data], { type: downType })
  const downloadElement = document.createElement('a')
  const href = window.URL.createObjectURL(blob)
  downloadElement.href = href
  document.body.appendChild(downloadElement)
  // downloadElement.setAttribute("download", downName);//设置下载名称
  downloadElement.download = downName // 设置下载文件名称
  downloadElement.click()
  document.body.removeChild(downloadElement) // 移除元素;防止连续点击创建多个a标签
  window.URL.revokeObjectURL(href)
}

判断电脑端移动端

JavaScript
const checkCurrentDeviceType = function () {
      let ua = navigator.userAgent.toLowerCase();
      let btypeInfo = (ua.match(/firefox|chrome|safari|opera/g) || 'other')[0];
      if ((ua.match(/msie|trident/g) || [])[0]) {
        btypeInfo = 'msie';
      }
      let pc = '';
      let prefix = '';
      let plat = '';
      //如果没有触摸事件 判定为PC
      let isTocuh = 'ontouchstart' in window || ua.indexOf('touch') !== -1 || ua.indexOf('mobile') !== -1;
      if (isTocuh) {
        if (ua.indexOf('ipad') !== -1) {
          pc = 'pad';
        } else if (ua.indexOf('mobile') !== -1) {
          pc = 'mobile';
        } else if (ua.indexOf('android') !== -1) {
          pc = 'androidPad';
        } else {
          pc = 'pc';
        }
      } else {
        pc = 'pc';
      }
      switch (btypeInfo) {
        case 'chrome':
        case 'safari':
        case 'mobile':
          prefix = 'webkit';
          break;
        case 'msie':
          prefix = 'ms';
          break;
        case 'firefox':
          prefix = 'Moz';
          break;
        case 'opera':
          prefix = 'O';
          break;
        default:
          prefix = 'webkit';
          break;
      }
      plat = ua.indexOf('android') > 0 ? 'android' : navigator.platform.toLowerCase();
      return {
        version: (ua.match(/[\s\S]+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1], //版本
        plat: plat, //系统
        type: btypeInfo, //浏览器
        pc: pc,
        prefix: prefix, //前缀
        isMobile: pc == 'pc' ? false : true, //是否是移动端
      };
    };
const checkCurrentDeviceType = function () {
      let ua = navigator.userAgent.toLowerCase();
      let btypeInfo = (ua.match(/firefox|chrome|safari|opera/g) || 'other')[0];
      if ((ua.match(/msie|trident/g) || [])[0]) {
        btypeInfo = 'msie';
      }
      let pc = '';
      let prefix = '';
      let plat = '';
      //如果没有触摸事件 判定为PC
      let isTocuh = 'ontouchstart' in window || ua.indexOf('touch') !== -1 || ua.indexOf('mobile') !== -1;
      if (isTocuh) {
        if (ua.indexOf('ipad') !== -1) {
          pc = 'pad';
        } else if (ua.indexOf('mobile') !== -1) {
          pc = 'mobile';
        } else if (ua.indexOf('android') !== -1) {
          pc = 'androidPad';
        } else {
          pc = 'pc';
        }
      } else {
        pc = 'pc';
      }
      switch (btypeInfo) {
        case 'chrome':
        case 'safari':
        case 'mobile':
          prefix = 'webkit';
          break;
        case 'msie':
          prefix = 'ms';
          break;
        case 'firefox':
          prefix = 'Moz';
          break;
        case 'opera':
          prefix = 'O';
          break;
        default:
          prefix = 'webkit';
          break;
      }
      plat = ua.indexOf('android') > 0 ? 'android' : navigator.platform.toLowerCase();
      return {
        version: (ua.match(/[\s\S]+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1], //版本
        plat: plat, //系统
        type: btypeInfo, //浏览器
        pc: pc,
        prefix: prefix, //前缀
        isMobile: pc == 'pc' ? false : true, //是否是移动端
      };
    };

判断手机是安卓还是IOS

JavaScript
/** 
 * 1: ios
 * 2: android
 * 3: 其它
 */
export const getOSType=() => {
  let u = navigator.userAgent, app = navigator.appVersion;
  let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
  let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  if (isIOS) {
    return 1;
  }
  if (isAndroid) {
    return 2;
  }
  return 3;
}
/** 
 * 1: ios
 * 2: android
 * 3: 其它
 */
export const getOSType=() => {
  let u = navigator.userAgent, app = navigator.appVersion;
  let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
  let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  if (isIOS) {
    return 1;
  }
  if (isAndroid) {
    return 2;
  }
  return 3;
}

手机号脱敏显示

JavaScript
export const hideMobile = (mobile) => {
  return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2")
}
export const hideMobile = (mobile) => {
  return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2")
}

节流函数

JavaScript
    /**
     *@Author:
     *@Description: 节流函数
     * @param { Function }   fn 需要节流函数
     * @param { Number }   wait 间隔时间差
     * @param { Function }   callback  此回调函数用于获取函数返回值
     */
   const throw = function (fn, wait, callback)  {
      let initTime = 0;
      return function () {
        let nowTime = Date.now();
        if ((nowTime = initTime >= wait)) {
          let res = fn.apply(this, [...arguments]);
          if (typeof callback == 'function') callback(res);
          initTime = nowTime;
        }
      };
    };
    /**
     *@Author:
     *@Description: 节流函数
     * @param { Function }   fn 需要节流函数
     * @param { Number }   wait 间隔时间差
     * @param { Function }   callback  此回调函数用于获取函数返回值
     */
   const throw = function (fn, wait, callback)  {
      let initTime = 0;
      return function () {
        let nowTime = Date.now();
        if ((nowTime = initTime >= wait)) {
          let res = fn.apply(this, [...arguments]);
          if (typeof callback == 'function') callback(res);
          initTime = nowTime;
        }
      };
    };

防抖函数

JavaScript
    /**
     *@Description: 防抖函数
     * @param { Function }   fn 需要防抖的函数
     * @param { Number }   wait 间隔时间差
     * @param { Boolean }   immediate 是否开始立即执行
     * @param { Function }   callback  此回调函数用于获取函数返回值
     */
   const debounce = function (fn, wait, immediate = false, callback)  {
      let timer = null;
      let ivoke = false;
      return function () {
        if (timer) clearTimeout(timer);
        if (immediate && !ivoke) {
          let res = fn.apply(this, [...arguments]);
          if (typeof callback == 'function') callback(res);
          ivoke = true;
        } else {
          timer = setTimeout(() => {
            let res = fn.apply(this, [...arguments]);
            if (typeof callback == 'function') callback(res);
            ivoke = true;
          }, wait);
        }
      };
    };
    /**
     *@Description: 防抖函数
     * @param { Function }   fn 需要防抖的函数
     * @param { Number }   wait 间隔时间差
     * @param { Boolean }   immediate 是否开始立即执行
     * @param { Function }   callback  此回调函数用于获取函数返回值
     */
   const debounce = function (fn, wait, immediate = false, callback)  {
      let timer = null;
      let ivoke = false;
      return function () {
        if (timer) clearTimeout(timer);
        if (immediate && !ivoke) {
          let res = fn.apply(this, [...arguments]);
          if (typeof callback == 'function') callback(res);
          ivoke = true;
        } else {
          timer = setTimeout(() => {
            let res = fn.apply(this, [...arguments]);
            if (typeof callback == 'function') callback(res);
            ivoke = true;
          }, wait);
        }
      };
    };

页面平滑滚动

JavaScript
// 自定义滚动动画
function smoothScroll (element) {
  // 获取需要滚动到的元素位置
  const targetPosition = element.offsetTop
  // 获取当前滚动条位置
  const startPosition = window.pageYOffset
  // 计算滚动距离和时间
  const distance = targetPosition - startPosition
  const duration = 500 // 滚动时间为0.5秒
  let start = null
  function step (timestamp) {
    if (!start) start = timestamp
    const progress = timestamp - start
    window.scrollTo(0, easeInOutCubic(progress, startPosition, distance, duration))
    if (progress < duration) window.requestAnimationFrame(step)
  }
  // 缓动函数
  function easeInOutCubic (t, b, c, d) {
    t /= d / 2
    if (t < 1) return c / 2 * t * t * t + b
    t -= 2
    return c / 2 * (t * t * t + 2) + b
  }
  window.requestAnimationFrame(step)
}

// 自带的smooth动画
export const smoothScroll = element =>{
    document.querySelector(element).scrollIntoView({
        behavior: 'smooth'
    });
};
// 自定义滚动动画
function smoothScroll (element) {
  // 获取需要滚动到的元素位置
  const targetPosition = element.offsetTop
  // 获取当前滚动条位置
  const startPosition = window.pageYOffset
  // 计算滚动距离和时间
  const distance = targetPosition - startPosition
  const duration = 500 // 滚动时间为0.5秒
  let start = null
  function step (timestamp) {
    if (!start) start = timestamp
    const progress = timestamp - start
    window.scrollTo(0, easeInOutCubic(progress, startPosition, distance, duration))
    if (progress < duration) window.requestAnimationFrame(step)
  }
  // 缓动函数
  function easeInOutCubic (t, b, c, d) {
    t /= d / 2
    if (t < 1) return c / 2 * t * t * t + b
    t -= 2
    return c / 2 * (t * t * t + 2) + b
  }
  window.requestAnimationFrame(step)
}

// 自带的smooth动画
export const smoothScroll = element =>{
    document.querySelector(element).scrollIntoView({
        behavior: 'smooth'
    });
};

滚动到页面顶部

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

大小写转换

JavaScript
// str 待转换的字符串
// type 1-全大写 2-全小写 3-首字母大写
export const turnCase = (str, type) => {
  switch (type) {
    case 1:
      return str.toUpperCase()
    case 2:
      return str.toLowerCase()
    case 3:
      return str[0].toUpperCase() + str.substring(1).toLowerCase()
    default:
      return str
  }
}
// str 待转换的字符串
// type 1-全大写 2-全小写 3-首字母大写
export const turnCase = (str, type) => {
  switch (type) {
    case 1:
      return str.toUpperCase()
    case 2:
      return str.toLowerCase()
    case 3:
      return str[0].toUpperCase() + str.substring(1).toLowerCase()
    default:
      return str
  }
}

解析URL参数

JavaScript
// 假设目前位于 https://****com/index?id=154513&age=18;
// getSearchParams(); // {id: "154513", age: "18"}

export const getSearchParams = () => {
  const searchPar = new URLSearchParams(window.location.search)
  const paramsObj = {}
  for (const [key, value] of searchPar.entries()) {
    paramsObj[key] = value
  }
  return paramsObj
}
// 假设目前位于 https://****com/index?id=154513&age=18;
// getSearchParams(); // {id: "154513", age: "18"}

export const getSearchParams = () => {
  const searchPar = new URLSearchParams(window.location.search)
  const paramsObj = {}
  for (const [key, value] of searchPar.entries()) {
    paramsObj[key] = value
  }
  return paramsObj
}

金额格式化

JavaScript
/*
*{number} number:要格式化的数字
*{number} decimals:保留几位小数
*{string} dec_point:小数点符号
*{string} thousands_sep:千分位符号
*/
export const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  const n = !isFinite(+number) ? 0 : +number
  const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
  const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep
  const dec = typeof dec_point === 'undefined' ? '.' : dec_point
  let s = ''
  const toFixedFix = function(n, prec) {
    const k = Math.pow(10, prec)
    return '' + Math.ceil(n * k) / k
  }
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  const re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2')
  }

  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}
/*
*{number} number:要格式化的数字
*{number} decimals:保留几位小数
*{string} dec_point:小数点符号
*{string} thousands_sep:千分位符号
*/
export const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  const n = !isFinite(+number) ? 0 : +number
  const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
  const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep
  const dec = typeof dec_point === 'undefined' ? '.' : dec_point
  let s = ''
  const toFixedFix = function(n, prec) {
    const k = Math.pow(10, prec)
    return '' + Math.ceil(n * k) / k
  }
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  const re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2')
  }

  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}

存储操作

JavaScript

class MyCache {
  constructor(isLocal = true) {
    this.storage = isLocal ? localStorage : sessionStorage
  }

  setItem(key, value) {
    if (typeof (value) === 'object') value = JSON.stringify(value)
    this.storage.setItem(key, value)
  }

  getItem(key) {
    try {
      return JSON.parse(this.storage.getItem(key))
    } catch (err) {
      return this.storage.getItem(key)
    }
  }

  removeItem(key) {
    this.storage.removeItem(key)
  }

  clear() {
    this.storage.clear()
  }

  key(index) {
    return this.storage.key(index)
  }

  length() {
    return this.storage.length
  }
}

const localCache = new MyCache()
const sessionCache = new MyCache(false)

export { localCache, sessionCache }

// localCache.getItem('user')
// sessionCache.setItem('name','树哥')
// sessionCache.getItem('token')
// localCache.clear()

class MyCache {
  constructor(isLocal = true) {
    this.storage = isLocal ? localStorage : sessionStorage
  }

  setItem(key, value) {
    if (typeof (value) === 'object') value = JSON.stringify(value)
    this.storage.setItem(key, value)
  }

  getItem(key) {
    try {
      return JSON.parse(this.storage.getItem(key))
    } catch (err) {
      return this.storage.getItem(key)
    }
  }

  removeItem(key) {
    this.storage.removeItem(key)
  }

  clear() {
    this.storage.clear()
  }

  key(index) {
    return this.storage.key(index)
  }

  length() {
    return this.storage.length
  }
}

const localCache = new MyCache()
const sessionCache = new MyCache(false)

export { localCache, sessionCache }

// localCache.getItem('user')
// sessionCache.setItem('name','树哥')
// sessionCache.getItem('token')
// localCache.clear()

模糊搜索

JavaScript
/*
* list 原数组
* keyWord 查询的关键词
* attribute 数组需要检索属性
*/

export const fuzzyQuery = (list, keyWord, attribute = 'name') => {
  const reg = new RegExp(keyWord)
  const arr = []
  for (let i = 0; i < list.length; i++) {
    if (reg.test(list[i][attribute])) {
      arr.push(list[i])
    }
  }
  return arr
}
/*
* list 原数组
* keyWord 查询的关键词
* attribute 数组需要检索属性
*/

export const fuzzyQuery = (list, keyWord, attribute = 'name') => {
  const reg = new RegExp(keyWord)
  const arr = []
  for (let i = 0; i < list.length; i++) {
    if (reg.test(list[i][attribute])) {
      arr.push(list[i])
    }
  }
  return arr
}

遍历树节点

JavaScript
export const foreachTree = (data, callback, childrenName = 'children') => {
  for (let i = 0; i < data.length; i++) {
    callback(data[i])
    if (data[i][childrenName] && data[i][childrenName].length > 0) {
      foreachTree(data[i][childrenName], callback, childrenName)
    }
  }
}


// 举例
foreachTree(data, (item) => {
  if (item.id === 9) {
    result = item
  }
})
console.log('result', result)  // {id: 9,label: "三级 1-1-1"}
export const foreachTree = (data, callback, childrenName = 'children') => {
  for (let i = 0; i < data.length; i++) {
    callback(data[i])
    if (data[i][childrenName] && data[i][childrenName].length > 0) {
      foreachTree(data[i][childrenName], callback, childrenName)
    }
  }
}


// 举例
foreachTree(data, (item) => {
  if (item.id === 9) {
    result = item
  }
})
console.log('result', result)  // {id: 9,label: "三级 1-1-1"}

精度计算

JavaScript
import Big from 'big.js'
 
function toFixed(num, precision) {
  return new Big(num).toFixed(precision)
}

// 验证
toFixed(1.45, 1)      // 输出:'1.5', 
toFixed(1158.725, 2)  // 输出:1158.73
import Big from 'big.js'
 
function toFixed(num, precision) {
  return new Big(num).toFixed(precision)
}

// 验证
toFixed(1.45, 1)      // 输出:'1.5', 
toFixed(1158.725, 2)  // 输出:1158.73

注意:利用这个方法,对于超过js最大安全整数的数,必须传入字符串。因为它都无法正确存储在内存中,所以必然会损失精度。如果要正确表示'181818181818181818.23',除非已知这个字符串,或者由后端返回该字符串才行。

JavaScript
toFixed('181818181818181818.23', 1)      // 输出: '181818181818181818.2'
toFixed('181818181818181818.23', 1)      // 输出: '181818181818181818.2'
AI助手