JavaScript开发小技巧
总结一些能够提高开发效率的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", "商品模块", "商品列表"]
JavaScript开发小技巧的更多相关文章
- 22条常用JavaScript开发小技巧
1.使用var声明变量 如果给一个没有声明的变量赋值,默认会作为一个全局变量(即使在函数内赋值).要尽量避免不必要的全局变量. 2.行尾使用分号 虽然JavaScript允许省略行尾的分号,但是有时不 ...
- Windows统一平台: 开发小技巧
Windows统一平台: 开发小技巧 技巧一: 在手机端拓展你应用的显示区域.(WP8.1中也适用) 对于Windows Phone系统的手机, 手机屏幕最上方为系统状态栏(System Tray), ...
- flex开发小技巧集锦
关于flex开发网上有非常多的相关信息介绍,因此我们要想学习关于flex开发的知识信息技能是一件非常简单和方便的事情.而针对于flex开发小编要告诉大家的是一些flex开发小技巧.利用这些小技巧能够有 ...
- TP开发小技巧
TP开发小技巧原文地址http://wp.chenyuanzhao.com/wp/2016/07/23/tp%E5%BC%80%E5%8F%91%E5%B0%8F%E6%8A%80%E5%B7%A7/ ...
- 移动Web开发小技巧
移动Web开发小技巧 添加到主屏后的标题(IOS) name="apple-mobile-web-app-title" content="标题"> 启用 ...
- BizTalk开发小技巧
BizTalk开发小技巧 随笔分类 - Biztalk Biztalk 使用BizTalk实现RosettaNet B2B So Easy 摘要: 使用BizTalk实现RosettaNet B2B ...
- Java开发小技巧(三):Maven多工程依赖项目
前言 本篇文章基于Java开发小技巧(二):自定义Maven依赖中创建的父工程project-monitor实现,运用我们自定义的依赖包进行多工程依赖项目的开发. 下面以多可执行Jar包项目的开发为例 ...
- iOS开发小技巧 - UILabel添加中划线
iOS开发小技巧 遇到的问题: 给Label添加中划线,然后并没有效果 NSString *str = [NSString stringWithFormat:@"合计金额 ¥%.2f&quo ...
- PHP开发小技巧②—实现二维数组根据key进行排序
在PHP中内置了很多对数组进行处理的函数,有很多时候我们直接使用其内置函数就能达到我们的需求,得到我们所想要的结果:但是,有的时候我们却不能通过使用内置函数实现我们的要求,这就需要我们自己去编写算法来 ...
随机推荐
- LinkedHashMap 的核心就 2 点,搞清楚,也就掌握了
HashMap 有一个不足之处就是在迭代元素时与插入顺序不一致.而大多数人都喜欢按顺序做某些事情,所以,LinkedHashMap 就是针对这一点对 HashMap 进行扩展,主要新增了「两种迭代方式 ...
- Lisp : (quote) code is data (eval) data as code
- 【JZOJ】2126. 最大约数和
题目大意 选取和不超过S的若干个不同的正整数,使得所有数的约数(不含它本身)之和最大. 分析 把我们分解出来的因数进行合并,存在一个不知名的数组里,然后我们大可开始我们的迪屁!!(bag),我们可以 ...
- 2019-09-11 redis命令【转载】
redis中添加key value元素:set key value; 获取元素:get key ; redis中添加集合:lpush key value1 value2 value3. ...
- logger.info占位符的使用
{}表示占位符,使用方法如下: package org.pine.controller; import javax.annotation.Resource; import org.pine.servi ...
- 使用gacutil把COM组件注册到全局缓存GAC中
我们在编写软件的时候,有时候需要调用COM组件,那就需要注册了,注册有两种,一种是使用regasm 在程序运行的时候注册,参考“pb调用C#编写的DLL类库“,不过受路径的限制.还有一种注册方式,使用 ...
- Zabbix监控服务器磁盘I/O
一.场景说明: 需要使用Zabbix监控服务器上各个磁盘的I/O使用率,当zabbix自身带的item无法满足我们的时候,则需自定义item. 包括: 磁盘读的次数 磁盘读的毫秒数 磁盘写的次 ...
- STM32系列芯片命名规范
1.STM32的基础知识 STM32是意法半导体公司,基于ARM Cortex®-M0,M0+,M3, M4和M7内核生产的系列通用MCU.截止当前时间为止(20190515),STM32有STM32 ...
- OpenLDAP 常用命令
OpenLDAP 常用命令 本文原始地址:https://sitoi.cn/posts/5308.html ldapsearch ldapsearch - ldap 搜索工具 ldapsearch 实 ...
- Peekaboo(2019年上海网络赛K题+圆上整点)
目录 题目链接 题意 思路 代码 题目链接 传送门 题意 你的位置在\(O(0,0)\),\(A\)的位置为\((x_1,y_1)\),\(B\)的位置为\((x_2,y_2)\),现在已知\(a=O ...