Loading... 工作中常用的js脚本,梳理一下,有需要的大家自取,有不足之处欢迎指正~ <div class="tip inlineBlock share"> 工具类 ```JavaScript // 往字符串指定位置插入元素 function insertStr (str1, n, str2) { let s1 = '' let s2 = '' if (str1.length < n) { return str1 + str2 } else { s1 = str1.substring(0, n) s2 = str1.substring(n, str1.length) return s1 + str2 + s2 } } /** * * @str<String>: str 原始字符串 * @character<String>: 去除的符号,默认为空格 * @type<String>: 去除的位置,默认为两边 * */ function trim (str, char, type) { if (char) { if (type === 'left') { return str.replace(new RegExp('^\\' + char + '+', 'g'), '') } else if (type === 'right') { return str.replace(new RegExp('\\' + char + '+$', 'g'), '') } return str.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '') } return str.replace(/^\s+|\s+$/g, '') } ``` </div> <div class="tip inlineBlock warning"> 日期时间类,依赖comment包 ```JavaScript import moment from 'moment' const formatDate = { formatDate (value, args) { const dt = new Date(value) if (args === 'yyyy-M-d') { // yyyy-M-d const year = dt.getFullYear() const month = dt.getMonth() + 1 const date = dt.getDate() return `${year}-${month}-${date}` } if (args === 'yyyy-M-d H:m:s') { // yyyy-M-d H:m:s const year = dt.getFullYear() const month = dt.getMonth() + 1 const date = dt.getDate() const hour = dt.getHours() const minute = dt.getMinutes() const second = dt.getSeconds() return `${year}-${month}-${date} ${hour}:${minute}:${second}` } if (args === 'yyyy-MM-dd') { // yyyy-MM-dd const year = dt.getFullYear() const month = (dt.getMonth() + 1).toString().padStart(2, '0') const date = dt.getDate().toString().padStart(2, '0') return `${year}-${month}-${date}` } // yyyy-MM-dd HH:mm:ss if (args === 'YYYYMMDD') { // yyyy-MM-dd const year = dt.getFullYear() const month = (dt.getMonth() + 1).toString().padStart(2, '0') const date = dt.getDate().toString().padStart(2, '0') return `${year}${month}${date}` } const year = dt.getFullYear() const month = (dt.getMonth() + 1).toString().padStart(2, '0') const date = dt.getDate().toString().padStart(2, '0') const hour = dt.getHours().toString().padStart(2, '0') const minute = dt.getMinutes().toString().padStart(2, '0') const second = dt.getSeconds().toString().padStart(2, '0') return `${year}-${month}-${date} ${hour}:${minute}:${second}` }, // 获取最近时间 type ['days', 'months'] recentDate (type = 'days', n = 1, format = 'YYYY-MM-DD', date = new Date()) { return moment(date).subtract(n, type).format(format) }, // 获取增加时间 type ['days', 'months'] addDate (type = 'days', n = 1, format = 'YYYY-MM-DD', date = new Date()) { return moment(date).add(n, type).format(format) }, // 判断格式是否为时间 2022-01-01 isValidDate (dateString) { return /^\d{4}-\d{2}-\d{2}$/.test(dateString) } } ``` </div> <div class="tip inlineBlock info"> 数据判断: ```JavaScript /** * 判断数据类型,统一以小写返回 */ function classOf (o) { if (o === null) return 'null' else return Object.prototype.toString.call(o).slice(8, -1).toLocaleLowerCase() } /** * 判断数据是否为空 */ function isEmpty (data) { const type = classOf(data) let flag = false switch (type) { case 'string': { flag = !data.length > 0 break } case 'undefined': { flag = true break } case 'null': { flag = true break } case 'boolean': { flag = data === false break } case 'object': { flag = !Object.keys(data).length > 0 break } case 'array': { flag = !data.length > 0 break } } return flag } /** * 判断两个数据是否相等 */ function isEqual (value1, value2) { if (value1 === value2) { return true } // 如果两个值类型不同,直接返回false if (classOf(value1) !== classOf(value2)) { return false } // 如果两个值都是对象 if (classOf(value1) === 'object' && classOf(value2) === 'object') { const keys1 = Object.keys(value1) const keys2 = Object.keys(value2) // 如果两个对象的属性数量不同,直接返回false if (keys1.length !== keys2.length) { return false } // 递归比较每个属性的值 for (const key of keys1) { if (!isEqual(value1[key], value2[key])) { return false } } // 所有属性的值都相等,返回true return true } // 如果两个值都是数组 if (classOf(value1) === 'array' && classOf(value2) === 'array') { if (value1.length !== value2.length) { return false } for (let i = 0; i < value1.length; i++) { if (!isEqual(value1[i], value2[i])) { return false } } return true } return value1 === value2 } // 数组中对象去重 function uniqueByAttr (arr, attr) { const res = new Map() return arr.filter((item) => !res.has(item[attr]) && res.set(item[attr], 1)) } // 数组去重 function unique (arr) { return arr.sort().reduce((init, current) => { if (init.length === 0 || init[init.length - 1] !== current) { init.push(current) } return init }, []) } ``` </div> <div class="tip inlineBlock warning"> 数结构数据处理 ```JavaScript /** * * @arr<Array>: 需要查找的数组 * @endNodeKey<String>: 数组中标识为末级的字段 * @endNodeValue<void>: 末级字段匹配的值 * @expectKey<String>: 需要获取数值的key * @childrenKey<String>: 子级的key * * */ function getEndNode (array, endNodeKey, endNodeKeyValue = true, expectKey, childrenKey = 'children') { const res = [] function _find (array) { array.forEach((item, index) => { if (item[endNodeKey] === endNodeKeyValue) { if (item[expectKey]) { res.push(item[expectKey]) } } else if (item[childrenKey] instanceof Array) { _find(item[childrenKey]) } }) } _find(array) return res } /** * * 树转列表 * @tree 需要转换tree * @attr 根据字段组合成树形, 默认根据id、name, parentId * * */ function treeToList (tree, attr = ['id', 'name', 'parentId']) { const list = [] const queue = [...tree] while (queue.length) { const node = queue.shift() const newNode = {} const children = node.children if (children) { queue.push(...children) delete node.children } attr.forEach((key) => { newNode[key] = node[key] }) list.push(newNode) } return list } /** * * 树列表前端搜索 * @tree 需要转换tree * @key 搜索关键字 * @attr 关键字映射的字段 * 返回新的树列表 * * */ function filterTree (tree, key, attr = 'name') { const filterChildrenTree = (resTree, treeItem) => { if (treeItem[attr].includes(key)) { resTree.push(treeItem) return resTree } if (Array.isArray(treeItem.children)) { const children = treeItem.children.reduce(filterChildrenTree, []) const data = { ...treeItem, children } if (children.length) { resTree.push({ ...data }) } } return resTree } return tree.reduce(filterChildrenTree, []) } /** * data 树形结构数据 * nodeKey 树形结构数据key * key 需要匹配的key * childrenField 子集key * */ function findNodeByKey (data, nodeKey, key, childrenField = 'children') { if (data && data.length) { for (let i = 0; i < data.length; i++) { const node = data[i] if (node[nodeKey] === key) { return node } else { const n = findNodeByKey(node[childrenField], nodeKey, key) if (n) { return n } } } } } // 树形结构收集指定的key function treeCollectsKeys (tree, collectKey = 'id', childrenKey = 'children', data = []) { if (tree) { data.push(tree[collectKey]) if (tree[childrenKey] && tree[childrenKey].length > 0) { tree[childrenKey].forEach((children) => { treeCollectsKeys(children, collectKey, childrenKey, data) }) } } return data } ``` </div> <div class="tip inlineBlock success"> url、传参处理 ```JavaScript /** * obj 转成 url拼接 * @param obj * @returns {string} */ function httpBuildUrl (obj) { const arr = [] for (const p in obj) { arr.push(encodeURIComponent(p) + '=' + obj[p]) } return arr.join('&') } ``` </div> 最后修改:2023 年 05 月 13 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 1 感谢赏赐的coffee~