JavaScript常用工具函数库汇总
导读
对象或数组的深拷贝
/** * 对象或数组的深拷贝 * @param {*} cloneObj 被克隆的对象 * @param {*} targetObj 克隆的目标对象 * @param {*} isOverride 若属性重复,是否覆盖被克隆对象的属性 */ function deepClone(cloneObj, targetObj, isOverride = true) { const _toString = Object.prototype.toString if (_toString.call(cloneObj) !== '[object Array]' && _toString.call(cloneObj) !== '[object Object]') { return cloneObj } var cloneTarget = _toString.call(cloneObj) === '[object Array]' ? [] : {} for (let key in cloneObj) { if (Object.prototype.hasOwnProperty.call(cloneObj, key)) { if (_toString.call(cloneObj[key]) === '[object Array]' || _toString.call(cloneObj[key]) === '[object Object]') { cloneTarget[key] = deepClone(cloneObj[key]) } else { cloneTarget[key] = cloneObj[key] } } } if (targetObj && (_toString.call(cloneObj) === _toString.call(targetObj))) { //这里要注意,克隆的目标对象也要deepClone下 cloneTarget = isOverride ? Object.assign(cloneTarget, deepClone(targetObj)) : Object.assign(deepClone(targetObj), cloneTarget) } return cloneTarget }
精准判断数据类型
//精准判断数据类型 function getVerifyDataTypes() { const types = ["String", "Number", "Boolean", "Null", "Undefined", "Function", "Object", "Array", "Date", "Error", "RegExp", "Symbol", "Map", "Set"] let Type = {} // 示例用法:Type.isString('javascript') for (let i = 0; i < types.length; i++) { Type[`is${types[i]}`] = obj => Object.prototype.toString.call(obj) === `[object ${types[i]}]` } // 判断字符串是否为json格式 Type.isJsonStr = str => { if (typeof str == 'string') { try { let obj = JSON.parse(str); if (obj && typeof obj == 'object') { return true; } return false; } catch (e) { return false; } } else { return false; } } return Type }
日期格式化
/** * 日期格式化 * @param {*} date 日期对象 * @param {*} beforeHyphen 年月日连字符 * @param {*} afterHyphen 时分秒连字符 */ function formatDate(date = new Date(), beforeHyphen = '-', afterHyphen = ':') { const formatNumber = n => { n = n.toString() return n[1] ? n : `0${n}` } const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hour = date.getHours() const minute = date.getMinutes() const second = date.getSeconds() const ymd = [year, month, day].map(formatNumber).join(beforeHyphen) const hms = [hour, minute, second].map(formatNumber).join(afterHyphen) return `${ymd} ${hms}` }
把时间戳转换为剩余的天、时、分、秒
/** * 把时间戳转换为剩余的天、时、分、秒,一般应用于倒计时场景中 * @param {*} timestamp 时间戳 */ function converTimestamp(timestamp) { const formatNumber = n => { n = n.toString() return n[1] ? n : `0${n}` } let day = Math.floor((timestamp / 1000 / 3600) / 24); let hour = Math.floor((timestamp / 1000 / 3600) % 24); let minute = Math.floor((timestamp / 1000 / 60) % 60); let second = Math.floor(timestamp / 1000 % 60); return { day: day, hour: formatNumber(hour), minute: formatNumber(minute), second: formatNumber(second) } }
从数组中随机取出一项
// 从数组中随机取出一项 function getRandomItemByArray(items) { return items[Math.floor(Math.random() * items.length)]; }
将有父子关系的数组转换成树形结构数据
let data = [ { parentId: 0, id: 1, value: 'xxx' }, { parentId: 1, id: 3, value: 'xxx' }, { parentId: 4, id: 6, value: 'xxx' }, { parentId: 3, id: 5, value: 'xxx' }, { parentId: 2, id: 4, value: 'xxx' }, { parentId: 1, id: 2, value: 'xxx' }, ] // 转换为树形Array结构 function toTreeAry(arr, pId = 0) { return arr .filter(({ parentId }) => parentId === pId) .map(a => ({ ...a, children: toTreeAry(arr.filter(({ parentId }) => parentId !== pId), a.id) })) } // 转换为树形Object结构 function toTreeObj(arr, pId = 0) { let res = {} arr.filter(({ parentId }) => parentId === pId) .forEach(a => { res[a.id] = { ...a, children: toTreeObj(arr.filter(({ parentId }) => parentId !== pId), a.id) } }) return res } console.log(toTreeAry(data)) console.log(toTreeObj(data))
生成随机字符串
// 随机字符串 const randomStr = () => { return new Date().getTime() + '-' + Math.random().toString(36).substr(2) }
过滤html标签
// 过滤html标签 const filterHTMLTag = (str) => { str = str.replace(/<\/?[^>]*>/g, ''); //去除HTML Tag str = str.replace(/[|]*\n/, '') //去除行尾空格 str = str.replace(/&npsp;/ig, ''); //去掉npsp return str; }
评论(0)