总结一些能够提高开发效率的JS技巧
1、过滤唯一值
Set类型是在ES6中新增的,它类似于数组,但是成员的值都是唯一的,没有重复的值。结合扩展运算符(...)我们可以创建一个新的数组,达到过滤原数组重复值的功能。
const array2 = [1, 2, 3, 3, 5, 5, 1]; const uniqueArray = [...new Set(array2)]; console.log(uniqueArray); // [1, 2, 3, 5]
2、转换Number类型
let testInt = "12"; testInt = +testInt; console.log(testInt); // Result: 12
3、截取数组,如果你知道原始数组的长度,就可以通过重新定义它的length属性来实现截取。
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; array.length = 4; console.log(array); // Result: [0, 1, 2, 3]
slice()方法的运行时更快。如果速度是你的主要目标,考虑使用下面的方式。
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; array = array.slice(0, 4); console.log(array); // Result: [0, 1, 2, 3]
4、获取数组中的最后的元素,数组方法slice()可以接受负整数,如果提供它,它将从数组的末尾开始截取数值,而不是开头。
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(array.slice(-1)); // Result: [9] console.log(array.slice(-2)); // Result: [8, 9] console.log(array.slice(-3)); // Result: [7, 8, 9]
5、是否为质数
const mathIsPrime = n => { if (n === 2 || n === 3) { return true } if (isNaN(n) || n <= 1 || n % 1 != 0 || n % 2 == 0 || n % 3 == 0) { return false; } for (let x = 6; x <= Math.sqrt(n) + 1; x += 6) { if (n % (x - 1) == 0 || n % (x + 1) == 0) { return false } } return true } mathIsPrime(0) // false
6、RGB色值生成16进制色值
const rgb2Hex = (r, g, b) => { r = Math.max(Math.min(Number(r), 100), 0) * 2.55 g = Math.max(Math.min(Number(g), 100), 0) * 2.55 b = Math.max(Math.min(Number(b), 100), 0) * 2.55 r = ('0' + (Math.round(r) || 0).toString(16)).slice(-2) g = ('0' + (Math.round(g) || 0).toString(16)).slice(-2) b = ('0' + (Math.round(b) || 0).toString(16)).slice(-2) return '#' + r + g + b } rgb2Hex(100, 50, 0) // "#ff7f00"
7、颜色混合
const colourBlend = (c1, c2, ratio) => { ratio = Math.max(Math.min(Number(ratio), 1), 0) let r1 = parseInt(c1.substring(1, 3), 16) let g1 = parseInt(c1.substring(3, 5), 16) let b1 = parseInt(c1.substring(5, 7), 16) let r2 = parseInt(c2.substring(1, 3), 16) let g2 = parseInt(c2.substring(3, 5), 16) let b2 = parseInt(c2.substring(5, 7), 16) let r = Math.round(r1 * (1 - ratio) + r2 * ratio) let g = Math.round(g1 * (1 - ratio) + g2 * ratio) let b = Math.round(b1 * (1 - ratio) + b2 * ratio) r = ('0' + (r || 0).toString(16)).slice(-2) g = ('0' + (g || 0).toString(16)).slice(-2) b = ('0' + (b || 0).toString(16)).slice(-2) return '#' + r + g + b } colourBlend('#ff0000', '#3333ff', 0.5) // "#991a80"
8、时间格式化
const dateFormatter = (formatter, date) => { date = (date ? new Date(date) : new Date) const Y = date.getFullYear() + '', M = date.getMonth() + 1, D = date.getDate(), H = date.getHours(), m = date.getMinutes(), s = date.getSeconds() return formatter.replace(/YYYY|yyyy/g, Y) .replace(/YY|yy/g, Y.substr(2, 2)) .replace(/MM/g, (M < 10 ? '0' : '') + M) .replace(/DD/g, (D < 10 ? '0' : '') + D) .replace(/HH|hh/g, (H < 10 ? '0' : '') + H) .replace(/mm/g, (m < 10 ? '0' : '') + m) .replace(/ss/g, (s < 10 ? '0' : '') + s) } dateFormatter('YYYY-MM-DD HH:mm', '2019/08/30 13:55') // 2019-08-30 13:55
9、树形结构数据,已知某一子节点 一次向上获取所有父节点
/** * 已知某一子节点 ,向上获取所有父节点 * @param {any} tree 树形结构数据 * @param {any} func 判断条件 * @param {any} path 返回的默认附加值 */ function treeFindParents(tree, func, path = []) { if (!tree) return [] for (const data of tree) { // 这里按照你的需求来存放最后返回的内容吧 path.push(data) if (func(data)) return path if (data.children) { const findChildren = treeFindParents(data.children, func, path) if (findChildren.length) return findChildren } path.pop() } return [] }
树形数据结构:
resData=[ { "parentId": "0", "id": "1e89edd7-69a0-4e09-9594-f9c8aac6ea4a", "url": "/Purchase/SkuDetail/SkuDetailIndex", "name": "首页", "children": [], "icon": "icon-hone" }, { "parentId": "0", "id": "8ee224f7-a995-4e60-b781-147c24a4be2c", "url": "#", "name": "商品模块", "children": [ { "parentId": "8ee224f7-a995-4e60-b781-147c24a4be2c", "id": "9c826d2c-bece-470f-b6ae-6bf99e1ade1c", "url": "/Supplier/Product_Spu/EditProduct", "name": "发布商品", "children": [], "icon": "icon-release-commodities" }, { "parentId": "8ee224f7-a995-4e60-b781-147c24a4be2c", "id": "78de0cff-2327-4a7a-875c-9a6fb0bf2341", "url": "/Supplier/Product_Spu/WaitProducts", "name": "待审核商品", "children": [], "icon": "icon-Commodities-examined" }, { "parentId": "8ee224f7-a995-4e60-b781-147c24a4be2c", "id": "989e309d-3dcc-4f1d-8230-2c8a72aca90c", "url": "/Supplier/Product_Spu/ProductList", "name": "商品列表", "children": [], "icon": "icon-product-list" } ], "icon": "el-icon-goods" }, { "parentId": "0", "id": "d77f9a2d-3fd4-49e6-b630-11fa75b89044", "url": "#", "name": "订单模块", "children": [ { "parentId": "d77f9a2d-3fd4-49e6-b630-11fa75b89044", "id": "d856fc34-3333-43d9-a5e0-ee157daaaaa8", "url": "/Purchase/PurchaseOrder/PurchaseOrderIndex", "name": "待接单列表", "children": [], "icon": "icon-Single-received" }, { "parentId": "d77f9a2d-3fd4-49e6-b630-11fa75b89044", "id": "eb3c76af-d9d1-4a30-8ee6-4c2f043c1638", "url": "/Purchase/SkuDetail/SkuDetailToBeShipped", "name": "待发货列表", "children": [], "icon": "icon-Waiting-list" }, { "parentId": "d77f9a2d-3fd4-49e6-b630-11fa75b89044", "id": "017af012-c59f-4f8c-a8b5-89696a82e7bf", "url": "/Purchase/SkuDetail/SkuDetailShipped", "name": "已发货列表", "children": [], "icon": "icon-received" } ], "icon": "el-icon-tickets" }, { "parentId": "0", "id": "d9976bfc-62ad-4f26-893d-9bfbc3efddae", "url": "#", "name": "账单模块", "children": [ { "parentId": "d9976bfc-62ad-4f26-893d-9bfbc3efddae", "id": "e8ce3c6b-7a4b-4be6-95ff-cd00d40a0ba5", "url": "/Bill/BillData/StayConfirmIndex", "name": "待确认账单", "children": [], "icon": "icon-Single-received" }, { "parentId": "d9976bfc-62ad-4f26-893d-9bfbc3efddae", "id": "ef438e69-2e14-4026-a004-1c723c482a28", "url": "/Bill/BillData/ConfirmedIndex", "name": "已确认账单", "children": [], "icon": "icon-Confirmed-bill" } ], "icon": "el-icon-menu" }, { "parentId": "0", "id": "f0bd7551-1338-4e0d-a959-21e893e9eacc", "url": "/Home/Index", "name": "首页", "children": [ { "parentId": "f0bd7551-1338-4e0d-a959-21e893e9eacc", "id": "e9431b41-7a86-4d4e-8c33-6ff635381699", "url": "/DashBoard/Introduction/IntroductionIndex", "name": "使用介绍", "children": [], "icon": "el-icon-question" }, { "parentId": "f0bd7551-1338-4e0d-a959-21e893e9eacc", "id": "78935279-4be8-4111-81e3-fe38c91eac4d", "url": "/DashBoard/ShowData/ShowDataIndex", "name": "数据统计", "children": [], "icon": "el-icon-info" } ], "icon": "el-icon-info" } ]
调用treeFindParents返回结果:
treeFindParents(resData, data=> data.id==='989e309d-3dcc-4f1d-8230-2c8a72aca90c',["888888","7777"]) //返回 ["888888", "7777", "商品模块", "商品列表"]