常用函数

130 阅读2分钟

防抖

let timeout = null
/**
 * 防抖原理:一定时间内,只有最后一次操作,再过wait毫秒后才执行函数
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
function debounce(func, wait = 500, immediate = false) {
    // 清除定时器
    if (timeout !== null) clearTimeout(timeout)
    // 立即执行,此类情况一般用不到
    if (immediate) {
        const callNow = !timeout
        timeout = setTimeout(() => {
            timeout = null
        }, wait)
        if (callNow) typeof func === 'function' && func()
    } else {
        // 设置定时器,当最后一次操作后,timeout不会再被清除,所以在延时wait毫秒后执行func回调方法
        timeout = setTimeout(() => {
            typeof func === 'function' && func()
        }, wait)
    }
}
export default debounce

节流

let timer; 
let flag;
/**
 * 节流原理:在一定时间内,只能触发一次
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
function throttle(func, wait = 500, immediate = true) {
    if (immediate) {
        if (!flag) {
            flag = true
            // 如果是立即执行,则在wait毫秒内开始时执行
            typeof func === 'function' && func()
            timer = setTimeout(() => {
                flag = false
            }, wait)
        }
    } else if (!flag) {
        flag = true
        // 如果是非立即执行,则在wait毫秒内的结束处执行
        timer = setTimeout(() => {
            flag = false
            typeof func === 'function' && func()
        }, wait)
    }
}
export default throttle

countTo

  function countTo({ startVal = 0, endVal, duration = 3000, timestamp = 0, callback }) {
    if (endVal === undefined) throw new Error('missing parameter "endVal" ')
    const easingFn = (t, b, c, d) => (c * (-Math.pow(2, (-10 * t) / d) + 1) * 1024) / 1023 + b
    const fn = (s) => countTo({ startVal, endVal, duration, timestamp: s, callback })

    let printVal = 0
    if (startVal < endVal) {
      printVal = easingFn(timestamp, startVal, endVal - startVal, duration)
    } else {
      printVal = startVal - easingFn(timestamp, 0, startVal - endVal, duration)
    }
    if (callback) {
      callback(timestamp > duration ? endVal : parseInt(printVal))
    }
    if (timestamp < duration) {
      window.requestAnimationFrame(fn)
    }
  }
  //使用
  countTo({
    startVal: 0,
    endVal: 100,
    duration: 2600,
    callback(val) {
      document.querySelector('.content').innerHTML = val
    }
  })

下载excel文件

function downLoadExcel(url, fileName, params = {}) {
  createAjax(url)(params, { responseType: 'blob' }).then((res) => {
    const elink = document.createElement('a')
    elink.download = `${fileName}.xlsx`
    elink.style.display = 'none'
    const blob = new Blob([res])
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    document.body.removeChild(elink)
  })
}

aes

import CryptoJS from 'crypto-js'

// aes解密
export function decrypt(str, keyword) {
  const keyStr = keyword
  const key = CryptoJS.enc.Utf8.parse(keyStr)
  const decrypted = CryptoJS.AES.decrypt(str, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return CryptoJS.enc.Utf8.stringify(decrypted).toString()
}
// aes加密
export function encrypt(str, keyword) {
  const keyStr = keyword // 判断是否存在ksy,不存在就用定义好的key
  const key = CryptoJS.enc.Utf8.parse(keyStr)
  const srcs = CryptoJS.enc.Utf8.parse(str)
  const encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return encrypted.toString()
}

严格的身份证校验

export const isCardID = (sId) => {
  if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(sId)) {
    console.log('你输入的身份证长度或格式错误')
    return false
  }
  // 身份证城市
  const aCity = {
    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: '国外',
  }
  if (!aCity[parseInt(sId.substr(0, 2))]) {
    console.log('你的身份证地区非法')
    return false
  }

  // 出生日期验证
  const sBirthday = (`${sId.substr(6, 4)}-${Number(sId.substr(10, 2))}-${Number(sId.substr(12, 2))}`).replace(/-/g, '/')
  const d = new Date(sBirthday)
  if (sBirthday != (`${d.getFullYear()}/${d.getMonth() + 1}/${d.getDate()}`)) {
    console.log('身份证上的出生日期非法')
    return false
  }

  // 身份证号码校验
  let sum = 0
  const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
  const codes = '10X98765432'
  for (let i = 0; i < sId.length - 1; i++) {
    sum += sId[i] * weights[i]
  }
  const last = codes[sum % 11] // 计算出来的最后一位身份证号码
  if (sId[sId.length - 1] != last) {
    console.log('你输入的身份证号非法')
    return false
  }

  return true
}

获取对象类型

export const getObjType = obj => {
var toString = Object.prototype.toString
var map = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regExp',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object'
}
if (obj instanceof Element) {
return 'element'
}
return map[toString.call(obj)]
}

深拷贝

export const deepClone = data => {
var type = getObjType(data)
var obj
if (type === 'array') {
obj = []
} else if (type === 'object') {
obj = {}
} else {
// 不再具有下一层次
return data
}
if (type === 'array') {
for (var i = 0, len = data.length; i < len; i++) {
obj.push(deepClone(data[i]))
}
} else if (type === 'object') {
for (var key in data) {
obj[key] = deepClone(data[key])
}
}
return obj
}

常用正则

金额:/^\d*(\.\d+)?$/

手机号:/^1[3|4|5|6|7|8|9][0-9]{9}$/

身份证:/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/

邮箱: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/

密码: /^[a-zA-Z]\w{5,17}$/

5-17位,字母开头,只能包含字母数字下划线

经度:/^[\-\+]?(0(\.\d{1,8})?|([1-9](\d)?)(\.\d{1,8})?|1[0-7]\d{1}(\.\d{1,8})?|180(([.][0]{1,8})?))$/

纬度:/^[\-\+]?((0|([1-8]\d?))(\.\d{1,8})?|90(\.0{1,8})?)$/

校验文件头

function fileReader (blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsBinaryString(blob);
    reader.onload = (ret) => {
      const res = reader.result.split('').map((o) => o.charCodeAt().toString(16).padStart(2, '0'));
      resolve(res.join(' ').toUpperCase());
    },
    reader.onerror = (err) => {
      console.log(err);
      reject(err);
    };
  });
};

//使用
 fileReader(file.slice(0, 8)).then(res=>{
    console.log(res==="89 50 4E 47 0D 0A 1A 0A");
  })

获取地址栏参数

function  GetQueryString(name)
{
      var  reg = new  RegExp( "(^|&)" + name + "=([^&]*)(&|$)" );
      var  r = window.location.search.substr(1).match(reg);
      if (r!= null ) return unescape(r[2]); 
      return  null ;
}

对象转成get参数

function queryObjToStr(obj) {
    let str = ''
    Object.keys(obj).forEach(key => {
      str += `${str ? '&' : '?'}${key}=${obj[key]}`
    })
    return str
  }