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中内置了很多对数组进行处理的函数,有很多时候我们直接使用其内置函数就能达到我们的需求,得到我们所想要的结果:但是,有的时候我们却不能通过使用内置函数实现我们的要求,这就需要我们自己去编写算法来 ...
随机推荐
- 优化、分析Mysql表读写、索引等操作的sql语句效率优化问题
为什么要优化: 随着实际项目的启动,数据库经过一段时间的运行,最初的数据库设置,会与实际数据库运行性能会有一些差异,这时我们 就需要做一个优化调整. 数据库优化这个课题较大,可分为四大类: >主 ...
- 后台数据转换成Excel,前台下载
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactI ...
- 有哪位大侠操作过NPOI生成word文档,如何设置页眉页脚距离顶部和底部距离?
#region 1.创建文档(页眉.页脚) XWPFDocument doc = new XWPFDocument(); //页面设置 A4:w=11906 h=16838 doc.Document. ...
- angular 监听离开页面执行相关操作
$scope.$on("$destroy", function() { //...})
- Asp.net MVC企业级开发(04)---SignalR消息推送
Asp.net SignalR是微软为实现实时通信而开发的一个类库.可以适用于以下场景: 聊天室,如在线客服系统,IM系统等 股票价格实时更新 消息的推送服务 游戏中人物位置的实时推送 SignalR ...
- 面试官:你知道Spring中有哪些可以让我们扩展的地方么
大家都知道我这段时间陆续更新了Spring系列源码分析以及各种扩展点的文章,到了今天可以总算可以更新这篇文章了 首先列举一下一个经典的面试题:Spring中Bean的生命周期: 开始初始化容器 加载B ...
- c/c++程序中内存区划分
转自:http://wenzongliang.iteye.com/blog/1866629 操作系统启动程序时会加载程序代码到内存(叫程序的代码区),然后创建进程PCB为进程分配内存资源(数据区,32 ...
- java常用IO流总结
- 0x03 Python logging模块之Formatter格式
目录 logging模块之Formatter格式 Formater对象 日志输出格式化字符串 LogRecoder对象 时间格式化字符串 logging模块之Formatter格式 在记录日志是,日志 ...
- js的函数三角恋
原创,转载请标明来源https://www.cnblogs.com/sogeisetsu/ js的函数三角恋 1.什么是构造函数 是专门用于创建对象的 对象就是object **** 1.什么是函数? ...