10条提高开发效率的JS技巧

更新日期: 2019-08-24阅读: 1.9k标签: 技巧

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


链接: https://www.fly63.com/article/detial/4918

微信小程序技巧_你需要知道的小程序开发技巧

一直以来进行了比较多的微信小程序开发... 总会接触到一些和官方组件或 api 相关或其无法解决的需求,于是决定在这里小小的整理一下微信小程序开发的一些技巧

微信小程序分享到朋友圈方法与技巧

小程序提供onShareAppMessage 函数,此函数只支持分享给我微信朋友,小程序如何分享到朋友圈呢?使用canvas绘制一张图片,并用wx.previewImage预览图片,然后长按图片保存图片到手机。

前端新手程序员不知道的 20个小技巧

前端新手程序员不知道的 20个小技巧:作为前端开发者,使用双显示器能大幅提高开发效率、学编程最好的语言不是PHP,是English、东西交付之前偷偷测试一遍、问别人之前最好先自己百度,google一下、把觉得不靠谱的需求放到最后做,很可能到时候需求就变了...

小技巧:检查你本地及公共 IP 地址

本地的 IP 地址是分配给你计算机上的内部硬件或虚拟网卡的本地/私有 IP 地址。根据你的 LAN 配置,上述 IP 地址可能是静态或动态的。公共的 IP 地址是你的 Internet 服务提供商(ISP)为你分配的公共/外部 IP 地址。

12 个 CSS 高级技巧汇总

使用 :not() 在菜单上应用/取消应用边框;给body添加行高;所有一切都垂直居中;逗号分隔的列表;使用负的 nth-child 选择项目;对图标使用SVG;优化显示文本;对纯CSS滑块使用 max-height;继承 box-sizing

26 个 jQuery使用技巧

禁用右键点击;禁用搜索文本框;新窗口打开链接;检测浏览器;预加载图片;样式筛选;列高度相同;字体大小调整;返回页面顶部;获取鼠标的xy坐标;验证元素是否为空;替换元素

提高网站加载速度的一些小技巧

为你网站的用户留下良好的第一印象是非常必要的。随着商业领域的竞争,拥有一个吸引人的网站可以帮助你脱颖而出。研究表明,如果加载时间超过3秒,会有 40% 的用户放弃访问你的网站

《CSS世界》中提到的实用技巧

清除浮动主要用于子元素浮动(float)之后,父元素无法撑起高度和宽度。文字少时居中,多时靠左因为div嵌套着p,所以p的尺寸并不会超过div。但是要注意,当p的内容为英文单词组成的时候

不常被提及的JavaScript小技巧

这次我们主要来分享11个在日常教程中不常被提及的JavaScript小技巧,他们往往在我们的日常工作中经常出现,但是我们又很容易忽略。Set类型是在ES6中新增的,它类似于数组,但是成员的值都是唯一的

CSS-in-JS 库 styled-class

为什么要在JavaScript里写CSS?避免命名全局污染,条件和动态样式(比如选择主题色之类的),在框架层面进行限制或补充(比如补全供应商前缀),避免业务人员使用奇技淫巧

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!