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

  1. [转载].NET开发常用的10条实用代码

    1.读取操作系统和CLR的版本 OperatingSystem os = System.Environment.OSVersion; Console.WriteLine(“Platform: {0}” ...

  2. 或许你不知道的10条SQL技巧(转自58沈剑原创)

    这几天在写索引,想到一些有意思的TIPS,希望大家有收获. 一.一些常见的SQL实践 (1)负向条件查询不能使用索引 select * from order where status!=0 and s ...

  3. 或许你不知道的10条SQL技巧

    一.一些常见的SQL实践 (1)负向条件查询不能使用索引 select * from order where status!=0 and stauts!=1 not in/not exists都不是好 ...

  4. Win Server 2003 10条小技巧

    微软推出Windows Server 2003已经有一段时间了,但是,由于它是一个面向企业用户的服务器操作系统,所以,没有引起更多个人用户的注意.实际上,简单地改变一下系统的设置,您也可以将Windo ...

  5. 你可能不知道的 10 条 SQL 技巧,涨知识了!

    转自:http://mp.weixin.qq.com/s?__biz=MjM5NzM0MjcyMQ==&mid=2650076293&idx=1&sn=38f6acc759df ...

  6. 10个JS技巧

    1.过滤唯一值 Set 对象是es6新引入的,配合扩展运算符[...]一起使用,我们可以用它来过滤数组的唯一值. const array = [1, 1, 2, 3, 5, 5, 1] const u ...

  7. (译)关于使用Eclipse Memory Analyzer的10点小技巧

    作者 Rave_Tian 2016.02.01 17:56* 字数 2988 阅读 520评论 0喜欢 0 分析和理解应用的内存使用情况是开发过程中一项不小的挑战.一个微小的逻辑错误可能会导致监听器没 ...

  8. 提升你的开发效率,10 个 NPM 使用技巧

    对于一个项目,常用的一些npm简单命令包含的功能有:初始化一个文件夹(npm init),下载npm模块(npm install),创建测试(npm test) 和自定义脚本(npm run).但是, ...

  9. 提升 Web开发性能的 10 个技巧

    随着网络的高速发展,网络性能的持续提高成为能否在芸芸App中脱颖而出的关键.高度联结的世界意味着用户对网络体验提出了更严苛的要求.假如你的网站不能做到快速响应,又或你的App存在延迟,用户很快就会移情 ...

随机推荐

  1. z = z*z + c的分型图如何画

    使用python的图形库. 环境:conda+jupyter notebook 代码如下: import numpy as np from PIL import Image from numba im ...

  2. rest framework 之渲染器

    根据 用户请求URL 或 用户可接受的类型,筛选出合适的 渲染组件. 用户请求头: Accept:text/html,application/xhtml+xml,application/xml;q=0 ...

  3. VS Code + MinGW + Clang + OpenGL (vscode 配置 opengl环境)

    vscode配置opengl环境会遇到一些问题,这里是在看了一些博文之后给出的一篇完整的可行的配置 首先,要配置C++环境,网上有很多完整的配置C++环境的教程,这里就引用一条 https://www ...

  4. 详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用

    https://blog.csdn.net/u012240455/article/details/80844361 注释介绍 @Cacheable @Cacheable 的作用 主要针对方法配置,能够 ...

  5. python生成测试报告HTMLTestRunner时报错ValueError: write to closed file的解决办法

    使用HTMLTestRunner时出现了以下问题: self.stream.write(output.encode('utf8')) ValueError: write to closed file ...

  6. 远程连接MySQL提示“Host is not allowed to connected to this MySQL server”

    如果你想连接你的mysql的时候发生这个错误: ERROR 1130: Host '192.168.1.3' is not allowed to connect to this MySQL serve ...

  7. php怎样应对高并发

    高并发下的数据安全 我们知道在多线程写入同一个文件的时候,会出现“线程安全”的问题(多个线程同时运行同一段代码,如果每次运行结果和单线程运行的结果是一样的,结果和预期相同,就是线程安全的). 如果是M ...

  8. Nginx是什么及作用?

    一:介绍 nginx是一个高性能的HTTP和反向代理服务器,其特点是占用内存少,并发能力强. 二:名词介绍 代理服务器: 代理服务器英文全称是Proxy Server,其功能就是代理网络用户去取得网络 ...

  9. 洛谷 P4158 [SCOI2009]粉刷匠 题解

    每日一题 day59 打卡 Analysis 很容易看出是一个dp, dp[i][j[k][0/1]来表示到了(i,j)时,刷了k次,0表示这个没刷,1表示刷了. 于是有转移: 1.换行时一定要重新刷 ...

  10. 浏览器正在等待locatehost的响应

    1.问题描述 在进行了几次增删改查操作后,浏览器显示浏览器正在等待locatehost的响应: 2.错误原因: 对数据库为关闭相应的资源. 3.解决方案: 关闭JDBC开启的资源: