讓你瞬間提高工作效率的常用JS函數(shù)匯總
前言
本文總結(jié)了項(xiàng)目開發(fā)過程中常用的js函數(shù)和正則,意在提高大家平時(shí)的開發(fā)效率,具體內(nèi)容如下:
- 常用的正則校驗(yàn)
- 常用的設(shè)備檢測(cè)方式
- 常用的日期時(shí)間函數(shù)
- 跨端事件處理
- js移動(dòng)端適配方案
- xss預(yù)防方式
- 常用的js算法(防抖,截流,去重,排序,模板渲染,觀察者...)
代碼
1.正則
- // 匹配郵箱
- let reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$
- // (新)匹配手機(jī)號(hào)
- let reg = /^1[0-9]{10}$/;
- // (舊)匹配手機(jī)號(hào)
- let reg = /^1(3|4|5|7|8)[0-9]{9}$/;
- // 匹配8-16位數(shù)字和字母密碼的正則表達(dá)式
- let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/;
- // 匹配國(guó)內(nèi)電話號(hào)碼 0510-4305211
- let reg = /\d{3}-\d{8}|\d{4}-\d{7}/;
- // 匹配身份證號(hào)碼
- let reg=/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
- // 匹配騰訊QQ號(hào)
- let reg = /[1-9][0-9]{4,}/;
- // 匹配ip地址
- let reg = /\d+\.\d+\.\d+\.\d+/;
- // 匹配中文
- let reg = /^[\u4e00-\u9fa5]*$/;
2.檢測(cè)平臺(tái)(設(shè)備)類型
- let isWechat = /micromessenger/i.test(navigator.userAgent),
- isWeibo = /weibo/i.test(navigator.userAgent),
- isQQ = /qq\//i.test(navigator.userAgent),
- isIOS = /(iphone|ipod|ipad|ios)/i.test(navigator.userAgent),
- isAndroid = /android/i.test(navigator.userAgent);
3.常用的日期時(shí)間函數(shù)
- // 時(shí)間格式化
- function format_date(timeStamp) {
- let date = new Date(timeStamp);
- return date.getFullYear() + "年"
- + prefix_zero(date.getMonth() + 1) + "月"
- + prefix_zero(date.getDate()) + "日 "
- + prefix_zero(date.getHours()) + ":"
- + prefix_zero(date.getMinutes());
- }
- // 數(shù)字格式化
- function prefix_zero(num) {
- return num >= 10 ? num : "0" + num;
- }
- // 倒計(jì)時(shí)時(shí)間格式化
- function format_time(timeStamp) {
- let day = Math.floor(timeStamp / (24 * 3600 * 1000));
- let leave1 = timeStamp % (24 * 3600 * 1000);
- let hours = Math.floor(leave1 / (3600 * 1000));
- let leave2 = leave1 % (3600 * 1000);
- let minutes = Math.floor(leave2 / (60 * 1000));
- let leave3 = leave2 % (60 * 1000);
- let seconds = Math.floor(leave3 / 1000);
- if (day) return day + "天" + hours + "小時(shí)" + minutes + "分";
- if (hours) return hours + "小時(shí)" + minutes + "分" + seconds + "秒";
- if (minutes) return minutes + "分" + seconds + "秒";
- if (seconds) return seconds + "秒";
- return "時(shí)間到!";
- }
5.跨端事件處理
- (function (doc, win) {
- var docEl = doc.documentElement,
- resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
- recalc = function () {
- var clientWidth = docEl.clientWidth;
- var fontSize = 20;
- docEl.style.fontSize = fontSize + 'px';
- var docStyles = getComputedStyle(docEl);
- var realFontSize = parseFloat(docStyles.fontSize);
- var scale = realFontSize / fontSize;
- console.log("realFontSize: " + realFontSize + ", scale: " + scale);
- fontSize = clientWidth / 667 * 20;
- if(isIphoneX()) fontSize = 19;
- fontSize = fontSize / scale;
- docEl.style.fontSize = fontSize + 'px';
- };
- // Abort if browser does not support addEventListener
- if (!doc.addEventListener) return;
- win.addEventListener(resizeEvt, recalc, false);
- doc.addEventListener('DOMContentLoaded', recalc, false);
- // iphoneX判斷
- function isIphoneX(){
- return /iphone/gi.test(navigator.userAgent) && (screen.height == 812 && screen.width == 375)
- }
- })(document, window);
6.xss預(yù)防方式
- // 敏感符號(hào)轉(zhuǎn)義
- function entities(s) {
- let e = {
- '"': '"',
- '&': '&',
- '<': '<',
- '>': '>'
- }
- return s.replace(/["<>&]/g, m => {
- return e[m]
- })
- }
7.常用的js算法
- /**
- * 節(jié)流函數(shù)--規(guī)定在一個(gè)單位時(shí)間內(nèi),只能觸發(fā)一次函數(shù)。如果這個(gè)單位時(shí)間內(nèi)觸發(fā)多次函數(shù),只有一次生效。
- */
- function throttle(fun, delay) {
- let last, deferTimer
- return function (args) {
- let that = this
- let _args = arguments
- let now = +new Date()
- if (last && now < last + delay) {
- clearTimeout(deferTimer)
- deferTimer = setTimeout(function () {
- last = now
- fun.apply(that, _args)
- }, delay)
- }else {
- last = now
- fun.apply(that,_args)
- }
- }
- }
- /**
- * 防抖函數(shù)--在事件被觸發(fā)n秒后再執(zhí)行回調(diào),如果在這n秒內(nèi)又被觸發(fā),則重新計(jì)時(shí)
- */
- function debounce(fun, delay) {
- return function (args) {
- let that = this
- clearTimeout(fun.id)
- fun.id = setTimeout(function () {
- fun.call(that, args)
- }, delay)
- }
- }
- // 觀察者模式
- let Observer = (function(){
- let t __messages = {};
- return {
- regist: function(type, fn) {
- if(typeof __messages[type] === 'undefined') {
- messages[type] = [fn];
- }else {
- __messages[type].push(fn);
- }
- },
- fire: function(type, args) {
- if(!__messages[type]){
- return
- }
- let events = {
- type: type,
- args: args || {}
- },
- i = 0,
- len = __messages[type].length;
- for(;i<len;i++){
- __messages[type][i].call(this, events);
- }
- },
- remove: function(type, fn) {
- if(__messages[type] instanceof Array){
- let i = __messages[type].length -1;
- for(;i>=0;i--){
- __messages[type][i] === fn && __messages[type].splice(i, 1)
- }
- }
- }
- }
- })();
- // 模板渲染方法
- function formatString(str, data) {
- return str.replace(/\{\{(\w+)\}\}/g, function(match, key) {
- return typeof data[key] === undefined ? '' : data[key]
- })
- }
- // 冒泡排序
- function bubbleSort(arr) {
- for (let i = arr.length - 1; i > 0; i--) {
- for (let j = 0; j < i; j++) {
- if (arr[j] > arr[j + 1]) {
- swap(arr, j, j + 1);
- }
- }
- }
- return arr;
- }
- // 置換函數(shù)
- function swap(arr, indexA, indexB) {
- [arr[indexA], arr[indexB]] = [arr[indexB], arr[indexA]];
- }
- // 數(shù)組去重
- function distinct(arr = testArr) {
- return arr.filter((v, i, array) => array.indexOf(v) === i)
- }
后期會(huì)繼續(xù)總結(jié)更多工作中遇到的經(jīng)典函數(shù),也作為自己在工作中的一點(diǎn)總結(jié)。我們當(dāng)然也可以直接使用lodash或ramda這些比較流行的函數(shù)式工具庫(kù),在這里僅做學(xué)習(xí)參考使用。
本文轉(zhuǎn)載自微信公眾號(hào)「趣談前端」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系趣談前端公眾號(hào)。