JavaScript常用工具函數(shù)庫匯總
對象或數(shù)組的深拷貝
/** * 對象或數(shù)組的深拷貝 * @param {*} cloneObj 被克隆的對象 * @param {*} targetObj 克隆的目標(biāo)對象 * @param {*} isOverride 若屬性重復(fù),是否覆蓋被克隆對象的屬性 */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))) { //這里要注意,克隆的目標(biāo)對象也要deepClone下 cloneTarget = isOverride ? Object.assign(cloneTarget, deepClone(targetObj)) : Object.assign(deepClone(targetObj), cloneTarget) } return cloneTarget}
精準(zhǔn)判斷數(shù)據(jù)類型
//精準(zhǔn)判斷數(shù)據(jù)類型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}`}
把時間戳轉(zhuǎn)換為剩余的天、時、分、秒
/** * 把時間戳轉(zhuǎn)換為剩余的天、時、分、秒,一般應(yīng)用于倒計時場景中 * @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) }}
從數(shù)組中隨機取出一項
// 從數(shù)組中隨機取出一項function getRandomItemByArray(items) { return items[Math.floor(Math.random() * items.length)];}
將有父子關(guān)系的數(shù)組轉(zhuǎn)換成樹形結(jié)構(gòu)數(shù)據(jù)
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’ },]// 轉(zhuǎn)換為樹形Array結(jié)構(gòu)function toTreeAry(arr, pId = 0) { return arr .filter(({ parentId }) => parentId === pId) .map(a => ({ ...a, children: toTreeAry(arr.filter(({ parentId }) => parentId !== pId), a.id) }))}// 轉(zhuǎn)換為樹形Object結(jié)構(gòu)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標(biāo)簽
// 過濾html標(biāo)簽const filterHTMLTag = (str) => { str = str.replace(/</?[^>]*>/g, ’’); //去除HTML Tag str = str.replace(/[|]*n/, ’’) //去除行尾空格 str = str.replace(/&npsp;/ig, ’’); //去掉npsp return str;}
以上就是JavaScript常用工具函數(shù)庫匯總的詳細(xì)內(nèi)容,更多關(guān)于JavaScript工具函數(shù)庫的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
