总结一些能够提高开发效率的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开发小技巧的更多相关文章

  1. 22条常用JavaScript开发小技巧

    1.使用var声明变量 如果给一个没有声明的变量赋值,默认会作为一个全局变量(即使在函数内赋值).要尽量避免不必要的全局变量. 2.行尾使用分号 虽然JavaScript允许省略行尾的分号,但是有时不 ...

  2. Windows统一平台: 开发小技巧

    Windows统一平台: 开发小技巧 技巧一: 在手机端拓展你应用的显示区域.(WP8.1中也适用) 对于Windows Phone系统的手机, 手机屏幕最上方为系统状态栏(System Tray), ...

  3. flex开发小技巧集锦

    关于flex开发网上有非常多的相关信息介绍,因此我们要想学习关于flex开发的知识信息技能是一件非常简单和方便的事情.而针对于flex开发小编要告诉大家的是一些flex开发小技巧.利用这些小技巧能够有 ...

  4. 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/ ...

  5. 移动Web开发小技巧

    移动Web开发小技巧 添加到主屏后的标题(IOS) name="apple-mobile-web-app-title" content="标题"> 启用  ...

  6. BizTalk开发小技巧

    BizTalk开发小技巧 随笔分类 - Biztalk Biztalk 使用BizTalk实现RosettaNet B2B So Easy 摘要: 使用BizTalk实现RosettaNet B2B ...

  7. Java开发小技巧(三):Maven多工程依赖项目

    前言 本篇文章基于Java开发小技巧(二):自定义Maven依赖中创建的父工程project-monitor实现,运用我们自定义的依赖包进行多工程依赖项目的开发. 下面以多可执行Jar包项目的开发为例 ...

  8. iOS开发小技巧 - UILabel添加中划线

    iOS开发小技巧 遇到的问题: 给Label添加中划线,然后并没有效果 NSString *str = [NSString stringWithFormat:@"合计金额 ¥%.2f&quo ...

  9. PHP开发小技巧②—实现二维数组根据key进行排序

    在PHP中内置了很多对数组进行处理的函数,有很多时候我们直接使用其内置函数就能达到我们的需求,得到我们所想要的结果:但是,有的时候我们却不能通过使用内置函数实现我们的要求,这就需要我们自己去编写算法来 ...

随机推荐

  1. 阿里云 OSS 如何设置防盗链, 上个月图床流量耗费50G+,请求次数10W+,什么鬼?

    欢迎关注个人微信公众号: 小哈学Java, 文末分享阿里 P8 高级架构师吐血总结的 <Java 核心知识整理&面试.pdf>资源链接!! 个人网站: https://www.ex ...

  2. Kafka学习笔记3--Kafka的生产者和消费者配置

    下载解压 kafka 后,在 kafka/config 下有 3 个配置文件与主题及其生产.消费相关. server.properties--服务端配置 producer.properties--生产 ...

  3. 记录RFID操作错误

    如果代码操作不了RFID设备,查看下通信协议的设置

  4. Go语言(golang)新发布的1.13中的Error Wrapping深度分析

    Go 1.13发布的功能还有一个值得深入研究的,就是对Error的增强,也是今天我们要分析的 Error Wrapping. 背景 做Go语言开发的,肯定经常用error,但是我们也知道error非常 ...

  5. php 读取excel 时间列

    用PHP做一个导入excel功能,发现读取excel时间列的时候总是数据不对,去网上查找了这个函数,转换了一下就好了,真尼玛迷茫了,什么情况,先记录一下,以后再研究吧. 函数如下: function ...

  6. 要什么 Photoshop,会这些 CSS 就够了

    标题党一时爽,一直标题党一直爽 还在上大学那会儿,我就喜欢玩 Photoshop.后来写网页的时候,由于自己太菜,好多花里胡哨的效果都得借助 Photoshop 实现,当时就特别希望 CSS 能像 P ...

  7. 英语CollaCoriiAsini阿胶CollaCoriiAsini单词

    阿胶(colla Corii Asini)始载于<神农本草经>,是马科动物驴的皮去毛后熬制而成的胶块,其性味甘.平,具有滋阴润肺,补血.止血等功效.主要治疗血虚萎黄,眩晕心悸,肌痿无力,心 ...

  8. 锁、分布式锁、无锁实战全局性ID

    1.为什么要使用锁 当发生并发时,会产生多线程争夺一个资源,为保证资源的唯一性. JVM锁:对象锁,死锁,重入锁,公平锁,偏向锁 分布式锁:数据库 nosql .zookeeper 面试题:如何排查死 ...

  9. 深入理解Java封装、继承、多态

    转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/10830957.html 一:封装 将类的某些信息隐藏在类内部,不允许外部程序直接访问,而是通过该类提供的方法 ...

  10. AB PLC简述

    一.  PLC基础概念 PLC:可编程序控制器是一种数字运算的电子系统,专为在工业环境下应用而设计.采用可编程的存储器,用来在内部存储执行逻辑运算.顺序控制.定时.计算和算术运算等操作的指令,并通过数 ...