總結一下自己用到的一些工具類
數據處理
關于淺拷貝和深拷貝更詳細的分析請查看:理解js的深拷貝和淺拷貝原理和實現的方法
淺拷貝
/** * 淺拷貝 * @param {Object} source * @returns {Object} */ function clone(source) { const result = Object.assign({}, source); return result; } module.exports = clone;
深拷貝
深拷貝的原理是一層層遍歷,直到所有數據都不可繼續下探。
/** * 深拷貝 * @param {*} source * @param {WeakMap} weakMap * @returns {*} target */ // 可遍歷對象 const iterations = [ '[object Object]', '[object Array]', '[object Map]', '[object Set]', ]; function cloneDeep(source, weakMap = new WeakMap()) { if (source === null) return source; // 獲取對象類型 const type = Object.prototype.toString.call(source); // 處理不可遍歷對象 if (!iterations.includes(type)) { if (type === '[object Date]') return new Date(source); if (type === '[object RegExp]') return new RegExp(source); if (type === '[object Symbol]') return Symbol(source.description); if (type === '[object Function]') return source; // 剩余的一般是原始類型,直接返回 return source; } // 創建 target 實例 let target = new source.constructor(); // {} | [] | Map(0) | Set(0) // 處理循環調用 const val = weakMap.get(source); if (val) return val; weakMap.set(source, target); if (type === '[object Map]') { source.forEach((value, key) => { target.set(key, cloneDeep(value)); }); return target; } if (type === '[object Set]') { source.forEach(value => { target.add(cloneDeep(value)); }); return target; } // 處理對象和數組 for (const key in source) { target[key] = cloneDeep(source[key], weakMap); } return target; } module.exports = cloneDeep;
任意范圍隨機數
/** * 生成指定范圍[min, max]的隨機數 * @param {Number} min * @param {Number} max * @return {Number} */ function randomNum(min, max) { if (min >= max) return min; min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } module.exports = randomNum;
數字轉百分比
/** * 轉換百分比 * @param {number} num * @param {number} total * @returns {string} 百分比 */ function toPercent(num, total) { let str = num >= 0 && total > 0 ? Number(((num / total) * 100).toFixed(2)) : 0; return str; } module.exports = toPercent;
文件單位自適應
/** * 文件大小單位適配,自動轉換B、K、M、G單位 * @param {number | string} fileSize 文件大小,以B為單位 * @returns {string} */ function translateFileSize(fileSize) { if (fileSize === null || typeof fileSize === 'undefined' || fileSize === '') { return '—'; } if (fileSize < 1024) { fileSize = fileSize + 'B'; } else if (fileSize < 1024 * 1024) { fileSize = Math.floor((fileSize * 10) / 1024) / 10 + 'K'; } else if (fileSize < 1024 * 1024 * 1024) { fileSize = Math.floor((fileSize * 10) / (1024 * 1024)) / 10 + 'M'; } else { fileSize = Math.floor((fileSize * 10) / (1024 * 1024 * 1024)) / 10 + 'G'; } return fileSize; } module.exports = translateFileSize;
金額處理
金額超出三位加逗號
/** * 金額超出三位加 ',' * @param {string} num 金額 * @param {string} locales 本地化配置,默認zh-CN * @param {object} options 本地化配置,默認{ style: 'currency', currency: 'CNY' } * @returns {string} */ function amountFormat( num, locales = 'zh-CN', options = { style: 'currency', currency: 'CNY' } ) { return num ? Number(num).toLocaleString(locales, options) : '0'; } module.exports = amountFormat;
事件處理
防抖
/** * 防抖 * * 用法: * const cbFun = debounce(fun, 2000) * cbFun() */ function debounce(fn, delay = 1000) { let timer = null; return function() { if (timer !== null) { clearTimeout(timer); } timer = setTimeout(() => { fn.apply(this, arguments); }, delay); }; } module.exports = debounce;
節流
/** * 節流 * * 用法: * const cbFun = throttle(fun, 2000) * cbFun() */ function throttle(fn, delay = 1000) { let old = 0; return function() { let now = new Date().valueOf(); if (now - old > delay) { fn.apply(this, arguments); old = now; } }; } module.exports = throttle;
定時器
var requestAnimFrame = (function() { return ( window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); } ); })(); /** * rAF 定時器 * * 用法: * const cbFun = rafInterval(fun, 2000) * cbFun() */ function rafInterval(fn, delay = 1000) { let start = 0; function fun() { const timestamp = new Date().valueOf(); if (start === undefined) start = timestamp; if (timestamp - start > delay) { start = timestamp; fn.apply(this, arguments); } requestAnimFrame(fun); } return function() { requestAnimFrame(fun); }; } module.exports = rafInterval;
文件處理
導出文件
/** * 導出文件 * @param {string} biteData 字節流 * @param {string} title 文件名 * @param {string} ext 文件后綴 */ function downloadFile(biteData, title = '導出', ext = 'xls') { let blob = new Blob([biteData], { type: 'application/octet-binary' }); let downloadElement = document.createElement('a'); let href = window.URL.createObjectURL(blob); downloadElement.target = '_blank'; downloadElement.href = href; downloadElement.download = `${title}.${ext}`; // 文件名 document.body.appendChild(downloadElement); downloadElement.click(); document.body.removeChild(downloadElement); window.URL.revokeObjectURL(href); // 釋放掉blob對象 } module.exports = downloadFile;
json導出csv文件
/** * JSON 數據轉成 CSV 文件導出 * @param {Array} list 要導出的JSON數據 * @param {Array} cols 表頭名稱,格式如:['ID', '姓名', '性別'],默認用第一條數據的key * @param {Array} keys 表頭使用的key,格式如:['id', 'name', 'gender'],需要和cols一一對應,否則導出數據有問題,默認用第一條數據的key * @param {string} fileName 導出的文件名稱,不含日期前綴和文件類型后綴的部分 * * 用法: * json2Csv(list, cols, keys, fileName) */ function json2Csv(list, cols, keys, fileName = '數據明細') { if ( !( list instanceof Array && cols instanceof Array && keys instanceof Array && typeof fileName === 'string' ) ) { console.log('參數格式錯誤'); return; } if (list.length === 0) return; if (cols.length === 0) cols = Object.keys(list[0]); if (keys.length === 0) keys = Object.keys(list[0]); fileName = fileName || '數據明細'; let title = cols; let jsonKey = keys; let data = list; let str = []; str.push(title.join(',') + '\n'); for (let i = 0; i < data.length; i++) { let temp = []; for (let j = 0; j < jsonKey.length; j++) { temp.push(data[i][jsonKey[j]]); } str.push(temp.join(',') + '\n'); } let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str.join('')); let downloadLink = document.createElement('a'); downloadLink.href = uri; downloadLink.download = new Date().toISOString().substring(0, 10) + '-' + fileName + '.csv'; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } module.exports = json2Csv;
正則校驗
郵箱
/** * 判斷郵箱格式 * @param {string} str * @returns {Boolean} */ function isEmailNum(str, type = 1) { return /^[A-Za-z0-9_\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/.test( str ); } module.exports = isEmailNum;
身份證
/** * 判斷是否為身份證號 * @param {string | number} str * @returns {Boolean} */ function isIdCard(str) { return /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test( str ); } module.exports = isIdCard;
手機號碼
/** * 判斷是否為電話號碼,會過濾掉空格和橫杠 * @param {string | number} str 手機號碼 * @returns {Boolean} */ function isPhoneNum(str, type = 1) { str = str .replace(/ /g, '') .replace(/-/g, '') .replace(/\(|\)|\(|\)/g, ''); // 去除空格、橫杠和括號 return /^(\+?0?86\-?)?1[3456789]\d{9}$/.test(str); } module.exports = isPhoneNum;
座機號碼
/** * 判斷是否為電話號碼,會過濾掉空格和橫杠 * @param {string | number} str 電話號碼 * @returns {Boolean} */ function isPhoneNum(str, type = 1) { str = str .replace(/ /g, '') .replace(/-/g, '') .replace(/\(|\)|\(|\)/g, ''); // 去除空格、橫杠和括號 return /^(\d{3,4})?[0-9]{7,8}$/.test(str); } module.exports = isPhoneNum;
以上僅僅是根據自己業務需求整理的,不一定適用所有項目,如有問題,歡迎指正~
聲明:
1. 本站所有文章教程及資源素材均來源于網絡與用戶分享或為本站原創,僅限用于學習和研究。
2. 如果內容損害你的權益請聯系客服QQ:1642748312給予處理。
碼云筆記 » 總結一下自己用到的一些工具類
1. 本站所有文章教程及資源素材均來源于網絡與用戶分享或為本站原創,僅限用于學習和研究。
2. 如果內容損害你的權益請聯系客服QQ:1642748312給予處理。
碼云筆記 » 總結一下自己用到的一些工具類