提升开发幸福感的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存在延迟,用户很快就会移情 ...
随机推荐
- Ubuntu下 安卓 adb 命令报:“insufficient permissions for device: user in plugdev group; ”问题的解决办法
https://blog.csdn.net/freezingxu/article/details/80893025 在接入设备进行联机调试的时候,遇到了这样的问题: insufficient perm ...
- 没有用到React,为什么我需要import引入React?
没有用到React,为什么我需要import引入React? 本质上来说JSX是React.createElement(component, props, ...children)方法的语法糖. 所以 ...
- centos7快速安装coreDns
1.下载二进制文件 wget https://github.com/coredns/coredns/releases/download/v1.5.0/coredns_1.5.0_linux_amd64 ...
- pt-online-schema-change 最佳实践(转)
pt的详细步骤 Step 1: Create the new table. Step 2: Alter the new, empty table. This should be very quick, ...
- Linux系统下jar包的启动方式
Linux 运行jar包命令如下: 方式一: Java -jar shareniu.jar 特点:当前ssh窗口被锁定,可按CTRL + C打断程序运行,或直接关闭窗口,程序退出 那如何让窗口不锁定? ...
- python应用-输入分数 输出最高分数对应的名字
def main(): names = ['刘备', '张飞', '曹操', '袁绍', '关羽', '赵云', '周瑜'] scores=[] num=0 m=0 for name in names ...
- 2019牛客暑期多校训练营(第五场)B:generator 1 (10进制快速幂)
题意:给定x0,x1,a,b,满足xi=a*xi-1+b*xi-2: 求xn,n<10^(10^6): 思路:10进制快速幂裸题.降幂来写好像也是可以的,但是循环节不是phi(mod),所以数学 ...
- C语言中一个语句太长用什么换行?
C语言中一个语句太长用什么换行? 5 C语言中一个语句太长用什么换行?比如我有一个printf语句很长很长,问了美观,我不想写在这一行了,要换到下一行,是不是在这行结尾的时候,要用个什么标识来表 ...
- 选择 IDE 的目的
选择 IDE 的目的 这个不消多说了, 在我看来,最重要的无非三点: 自动补全 自定义模板(俗称 custom snippets) IDE 内 debug. 代码静态检查(错误提示,这里主要包括 es ...
- Async programming
Asynchrony, in computer programming, refers to the occurrence of events independent of the mainprogr ...