当前位置:主页 > 查看内容

让你瞬间提高工作效率的常用JS函数汇总

发布时间:2021-09-05 00:00| 位朋友查看

简介:前言 本文总结了项目开发过程中常用的js函数和正则,意在提高大家平时的开发效率,具体内容如下: 常用的正则校验 常用的设备检测方式 常用的日期时间函数 跨端事件处理 js移动端适配方案 xss预防方式 常用的js算法(防抖,截流,去重,排序,模板渲染,观察……

 

前言

本文总结了项目开发过程中常用的js函数和正则,意在提高大家平时的开发效率,具体内容如下:

  1. 常用的正则校验
  2. 常用的设备检测方式
  3. 常用的日期时间函数
  4. 跨端事件处理
  5. js移动端适配方案
  6. xss预防方式
  7. 常用的js算法(防抖,截流,去重,排序,模板渲染,观察者...)

代码

1.正则

  1. // 匹配邮箱 
  2. let reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$ 
  3.  
  4. // (新)匹配手机号 
  5. let reg = /^1[0-9]{10}$/; 
  6.  
  7. // (旧)匹配手机号 
  8. let reg = /^1(3|4|5|7|8)[0-9]{9}$/; 
  9.  
  10. // 匹配8-16位数字和字母密码的正则表达式 
  11. let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/; 
  12.  
  13. // 匹配国内电话号码 0510-4305211 
  14. let reg = /\d{3}-\d{8}|\d{4}-\d{7}/; 
  15.  
  16. // 匹配身份证号码 
  17. let reg=/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; 
  18.  
  19. // 匹配腾讯QQ号 
  20. let reg = /[1-9][0-9]{4,}/; 
  21.  
  22. // 匹配ip地址 
  23. let reg = /\d+\.\d+\.\d+\.\d+/; 
  24.  
  25. // 匹配中文 
  26. let reg = /^[\u4e00-\u9fa5]*$/; 

2.检测平台(设备)类型

  1. let isWechat = /micromessenger/i.test(navigator.userAgent), 
  2.     isWeibo = /weibo/i.test(navigator.userAgent), 
  3.     isQQ = /qq\//i.test(navigator.userAgent), 
  4.     isIOS = /(iphone|ipod|ipad|ios)/i.test(navigator.userAgent), 
  5.     isAndroid = /android/i.test(navigator.userAgent); 

3.常用的日期时间函数

  1. // 时间格式化 
  2. function format_date(timeStamp) { 
  3.     let date = new Date(timeStamp); 
  4.     return date.getFullYear() + "年" 
  5.         + prefix_zero(date.getMonth() + 1) + "月" 
  6.         + prefix_zero(date.getDate()) + "日 " 
  7.         + prefix_zero(date.getHours()) + ":" 
  8.         + prefix_zero(date.getMinutes()); 
  9.  
  10. // 数字格式化 
  11. function prefix_zero(num) { 
  12.     return num >= 10 ? num : "0" + num; 
  13.  
  14. // 倒计时时间格式化 
  15. function format_time(timeStamp) { 
  16.     let day = Math.floor(timeStamp / (24 * 3600 * 1000)); 
  17.     let leave1 = timeStamp % (24 * 3600 * 1000); 
  18.     let hours = Math.floor(leave1 / (3600 * 1000)); 
  19.     let leave2 = leave1 % (3600 * 1000); 
  20.     let minutes = Math.floor(leave2 / (60 * 1000)); 
  21.     let leave3 = leave2 % (60 * 1000); 
  22.     let seconds = Math.floor(leave3 / 1000); 
  23.     if (dayreturn day + "天" + hours + "小时" + minutes + "分"
  24.     if (hours) return hours + "小时" + minutes + "分" + seconds + "秒"
  25.     if (minutes) return minutes + "分" + seconds + "秒"
  26.     if (seconds) return seconds + "秒"
  27.     return "时间到!"

5.跨端事件处理

  1. (function (doc, win) { 
  2.     var docEl = doc.documentElement, 
  3.         resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize'
  4.         recalc = function () { 
  5.             var clientWidth = docEl.clientWidth; 
  6.             var fontSize = 20; 
  7.             docEl.style.fontSize = fontSize + 'px'
  8.             var docStyles = getComputedStyle(docEl); 
  9.             var realFontSize = parseFloat(docStyles.fontSize); 
  10.             var scale = realFontSize / fontSize; 
  11.             console.log("realFontSize: " + realFontSize + ", scale: " + scale); 
  12.             fontSize = clientWidth / 667 * 20; 
  13.             if(isIphoneX()) fontSize = 19; 
  14.             fontSize = fontSize / scale; 
  15.             docEl.style.fontSize = fontSize + 'px'
  16.         }; 
  17.     // Abort if browser does not support addEventListener 
  18.     if (!doc.addEventListener) return
  19.     win.addEventListener(resizeEvt, recalc, false); 
  20.     doc.addEventListener('DOMContentLoaded', recalc, false); 
  21.  
  22.     // iphoneX判断 
  23.     function isIphoneX(){ 
  24.         return /iphone/gi.test(navigator.userAgent) && (screen.height == 812 && screen.width == 375) 
  25.     } 
  26.  
  27. })(document, window); 

6.xss预防方式

  1. // 敏感符号转义 
  2. function entities(s) { 
  3.     let e = { 
  4.         '"''"'
  5.         '&''&'
  6.         '<''&lt;'
  7.         '>''&gt;' 
  8.     } 
  9.     return s.replace(/["<>&]/g, m => { 
  10.         return e[m] 
  11.     }) 

7.常用的js算法

  1. /** 
  2.  * 节流函数--规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。 
  3.  */ 
  4. function throttle(fun, delay) { 
  5.     let last, deferTimer 
  6.     return function (args) { 
  7.         let that = this 
  8.         let _args = arguments 
  9.         let now = +new Date() 
  10.         if (last && now < last + delay) { 
  11.             clearTimeout(deferTimer) 
  12.             deferTimer = setTimeout(function () { 
  13.                 last = now 
  14.                 fun.apply(that, _args) 
  15.             }, delay) 
  16.         }else { 
  17.             last = now 
  18.             fun.apply(that,_args) 
  19.         } 
  20.     } 
  21.  
  22. /** 
  23.  * 防抖函数--在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时 
  24.  */ 
  25.  function debounce(fun, delay) { 
  26.     return function (args) { 
  27.         let that = this 
  28.         clearTimeout(fun.id) 
  29.         fun.id = setTimeout(function () { 
  30.             fun.call(that, args) 
  31.         }, delay) 
  32.     } 
  33.  
  34. // 观察者模式 
  35. let Observer = (function(){ 
  36.   let t __messages = {}; 
  37.   return { 
  38.     regist: function(type, fn) { 
  39.       if(typeof __messages[type] === 'undefined') { 
  40.         messages[type] = [fn]; 
  41.       }else { 
  42.         __messages[type].push(fn); 
  43.       } 
  44.     }, 
  45.     fire: function(type, args) { 
  46.       if(!__messages[type]){ 
  47.         return 
  48.       } 
  49.       let events = { 
  50.         type: type, 
  51.         args: args || {} 
  52.       }, 
  53.       i = 0, 
  54.       len = __messages[type].length; 
  55.       for(;i<len;i++){ 
  56.         __messages[type][i].call(this, events); 
  57.       } 
  58.     }, 
  59.     remove: function(type, fn) { 
  60.       if(__messages[type] instanceof Array){ 
  61.         let i = __messages[type].length -1; 
  62.         for(;i>=0;i--){ 
  63.           __messages[type][i] === fn && __messages[type].splice(i, 1) 
  64.         } 
  65.       } 
  66.     } 
  67.   } 
  68. })(); 
  69.  
  70.  // 模板渲染方法 
  71.  function formatString(str, data) { 
  72.    return str.replace(/\{\{(\w+)\}\}/g, function(match, key) { 
  73.      return typeof data[key] === undefined ? '' : data[key
  74.    }) 
  75.  } 
  76.   
  77.  // 冒泡排序 
  78. function bubbleSort(arr) { 
  79.     for (let i = arr.length - 1; i > 0; i--) { 
  80.       for (let j = 0; j < i; j++) { 
  81.         if (arr[j] > arr[j + 1]) { 
  82.           swap(arr, j, j + 1); 
  83.         } 
  84.       } 
  85.     } 
  86.     return arr; 
  87.  
  88. // 置换函数 
  89. function swap(arr, indexA, indexB) { 
  90.     [arr[indexA], arr[indexB]] = [arr[indexB], arr[indexA]]; 
  91.  
  92. // 数组去重 
  93. function distinct(arr = testArr) { 
  94.     return arr.filter((v, i, array) => array.indexOf(v) === i) 

后期会继续总结更多工作中遇到的经典函数,也作为自己在工作中的一点总结。我们当然也可以直接使用lodash或ramda这些比较流行的函数式工具库,在这里仅做学习参考使用。

本文转载自微信公众号「趣谈前端」,可以通过以下二维码关注。转载本文请联系趣谈前端公众号。


本文转载自网络,原文链接:https://mp.weixin.qq.com/s/MKNJPrH9mI-AQFUIpANZNg
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文

  • 周排行
  • 月排行
  • 总排行

随机推荐