鱼头总结一些能够提高开发效率的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

最新文章

  1. C# Delegate 匿名 Delegate
  2. wordpress添加文章浏览统计(刷新不重复)
  3. jquery 展开折叠菜单
  4. 采用CSS3设计的登陆界面
  5. BZOJ 1452: [JSOI2009]Count 二维树状数组
  6. Datazen 自定义地图--中国地图
  7. iOS 除去图片的白色背景(接近白色),或者其它颜色的替换,获取像素点的ARGB值
  8. linux脚本实例之while
  9. LeetCode 74. Search a 2D Matrix(搜索二维矩阵)
  10. NYOJ 2357: 插塔憋憋乐 贪心
  11. GotoAndPlay
  12. Check the string CodeForces - 960A
  13. ad network 和 ad exchange 的对比
  14. js证书批量生成与打包下载
  15. 《Tensorflow从入门到精通》
  16. 3里氏代换原则LSP
  17. 论文笔记之:Heterogeneous Face Attribute Estimation: A Deep Multi-Task Learning Approach
  18. shell-url-decode
  19. 熟悉SQL Server 数据类型
  20. .Net Framework4.0 ashx页面报错:检测到有潜在危险的Request.Form值

热门文章

  1. Scroller——startScroll、fling(惯性滑动)
  2. python基础-os模块
  3. Docker搭建Adminer(数据库图形化管理界面)
  4. Ubuntu中wine程序安装windows软件中文乱码如何解决
  5. ELK快速入门(二)通过logstash收集日志
  6. zabbix--显示插件Graphtree
  7. zabbix--自动注册
  8. 基于gin web框架搭建RESTful API服务
  9. Beta冲刺阶段博客集合
  10. node 文件上传