提升开发幸福感的10条JS技巧
鱼头总结一些能够提高开发效率的JS技巧,这些技巧很实用,觉得挺好,想推荐给大家,所以有了这篇文章。
生成随机UID
const genUid = () => {
var length = 20
var soupLength = genUid.soup_.length
var id = []
for (var i = 0; i < length; i++) {
id[i] = genUid.soup_.charAt(Math.random() * soupLength)
}
return id.join('')
}
genUid.soup_ = '!#$%()*+,-./:;=?@[]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
genUid() // ;l`yCPc9A8IuK}?N6,%}
无loop生成指定长度的数组
const List = len => [...new Array(len).keys()]
const list = List(10) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
一行代码去重数组
const list = [1, 1, 2, 3, 6, 45, 8, 5, 4, 6, 5]
const uniqueList = [...new Set(list)] // [1, 2, 3, 6, 45, 8, 5, 4]
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"
颜色混合
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"
判断是否为质数
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) // true
遍历类数组对象
const elements = document.querySelectorAll(selector);
[].prototype.forEach.call(elements, (el, idx, list) => {
console.log(el) // 元素节点
})
判断对象类型
const type = data => Object.prototype.toString.call(data).replace(/^\[object (.+)\]$/, '$1').toLowerCase()
type({}) // object
优化多层判断条件
const getScore = score => {
const scoreData = new Array(101).fill(0)
.map((data, idx) => ([idx, () => (idx < 60 ? '不及格' : '及格')]))
const scoreMap = new Map(scoreData)
return (scoreMap.get(score)
? scoreMap.get(score)()
: '未知分数')
}
getScore(30) // 不及格
时间格式化
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', '1995/02/15 13:55') // 1995-02-15 13:55
后记
以上十个技巧都是我在日常开发中经常用到的一些代码片段,善用这些技巧,可以大大减少我们的开发时间。如果此时正在看文章的你也有类似的技巧心得,不妨在下方留言来分享给大家。
如果你、喜欢探讨技术,或者对本文有任何的意见或建议,你可以扫描下方二维码,关注微信公众号“鱼头的Web海洋”,随时与鱼头互动。欢迎!衷心希望可以遇见你。
原文地址:https://mp.weixin.qq.com/s/Ir9Q1KgOBkf2MBu6bN4L1w
提升开发幸福感的10条JS技巧的更多相关文章
- [转载].NET开发常用的10条实用代码
1.读取操作系统和CLR的版本 OperatingSystem os = System.Environment.OSVersion; Console.WriteLine(“Platform: {0}” ...
- 或许你不知道的10条SQL技巧(转自58沈剑原创)
这几天在写索引,想到一些有意思的TIPS,希望大家有收获. 一.一些常见的SQL实践 (1)负向条件查询不能使用索引 select * from order where status!=0 and s ...
- 或许你不知道的10条SQL技巧
一.一些常见的SQL实践 (1)负向条件查询不能使用索引 select * from order where status!=0 and stauts!=1 not in/not exists都不是好 ...
- Win Server 2003 10条小技巧
微软推出Windows Server 2003已经有一段时间了,但是,由于它是一个面向企业用户的服务器操作系统,所以,没有引起更多个人用户的注意.实际上,简单地改变一下系统的设置,您也可以将Windo ...
- 你可能不知道的 10 条 SQL 技巧,涨知识了!
转自:http://mp.weixin.qq.com/s?__biz=MjM5NzM0MjcyMQ==&mid=2650076293&idx=1&sn=38f6acc759df ...
- 10个JS技巧
1.过滤唯一值 Set 对象是es6新引入的,配合扩展运算符[...]一起使用,我们可以用它来过滤数组的唯一值. const array = [1, 1, 2, 3, 5, 5, 1] const u ...
- (译)关于使用Eclipse Memory Analyzer的10点小技巧
作者 Rave_Tian 2016.02.01 17:56* 字数 2988 阅读 520评论 0喜欢 0 分析和理解应用的内存使用情况是开发过程中一项不小的挑战.一个微小的逻辑错误可能会导致监听器没 ...
- 提升你的开发效率,10 个 NPM 使用技巧
对于一个项目,常用的一些npm简单命令包含的功能有:初始化一个文件夹(npm init),下载npm模块(npm install),创建测试(npm test) 和自定义脚本(npm run).但是, ...
- 提升 Web开发性能的 10 个技巧
随着网络的高速发展,网络性能的持续提高成为能否在芸芸App中脱颖而出的关键.高度联结的世界意味着用户对网络体验提出了更严苛的要求.假如你的网站不能做到快速响应,又或你的App存在延迟,用户很快就会移情 ...
随机推荐
- 字符串转换成float和double类型
double strtod(const char *nptr, char **endptr); float strtof(const char *nptr, char **endptr); long ...
- 量化金融策略开源框架:QUANTAXIS
简介: QUANTAXIS量化金融策略框架,是一个面向中小型策略团队的量化分析解决方案,是一个从数据爬取.清洗存储.分析回测.可视化.交易复盘的本地一站式解决方案. QUANTAXIS量化金融策略框架 ...
- Python数据预处理之清及
使用Pandas进行数据预处理 数据清洗中不是每一步都是必须的,按实际需求操作. 内容目录 1.数据的生成与导入 2.数据信息查看 2.1.查看整体数据信息 2.2.查看数据维度.列名称.数据格式 2 ...
- io详解
1.io类
- HTTPS 原理及配置
目录 一.HTTPS 身份验证介绍 二.windows 环境下配置 tomcat HTTPS 三.linux 环境下配置 tomcat HTTPS 一.HTTPS 身份验证介绍 1. HTTPS 原理 ...
- Mysql 控制结构初识
Mysql 流程控制 认识 从我目前所接触的编程语言,C, R, VB, Python, Javascript...,来看, 无非就是变量, 表达式, 流程控制(顺序, 分支, 循环), 封装了一些更 ...
- idea导入mybatis源码
1.最近在学mybatis,想下载源码导入idea结果网上一查没有一篇完整的,结果让我进了个大坑,算了,废话少说 2.两种办法,一个是git客户端克隆,另外一个是下载code压缩包.先说通过git客户 ...
- jmeter 实现登录参数化
业务场景 在测试过程中,一般需要模拟不同的用户登录,这样压测的数据比较平均,也能更好的模拟真实的压力情况. 如果使用同一个用户账号进行测试,那么比如在查询代办的时候,此人的待办太多,也不符合实际的情况 ...
- springboot+jndi+tomcat配置多数据源
1.在application.properties中,添加jndi配置,如下图 2.新建dataSourceConfig类 3.dataSourceConfig类详细代码,这里只贴出其中一个,多个数据 ...
- Fedora 安装 MongoDB 教程
MongoDB 安装 本文原始地址:https://sitoi.cn/posts/37161.html 安装环境 Fedora 29 安装步骤 安装 mongodb 和 mongodb-server ...