15条你可能不知道的JS高效技巧
web前端开发
共 3868字,需浏览 8分钟
· 2020-08-13
1、延迟函数delay
const delay = ms => new Promise((resolve, reject) => setTimeout(resolve, ms))
const getData = status => new Promise((resolve, reject) => {
status ? resolve('done') : reject('fail')
})
const getRes = async (data) => {
try {
const res = await getData(data)
const timestamp = new Date().getTime()
await delay(1000)
console.log(res, new Date().getTime() - timestamp)
} catch (error) {
console.log(error)
}
}
getRes(true) // 隔了1秒
2、分割指定长度的元素数组
const listChunk = (list, size = 1, cacheList = []) => {
const tmp = [...list]
if (size <= 0) {
return cacheList
}
while (tmp.length) {
cacheList.push(tmp.splice(0, size))
}
return cacheList
}
console.log(listChunk([1, 2, 3, 4, 5, 6, 7, 8, 9])) // [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
console.log(listChunk([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)) // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
console.log(listChunk([1, 2, 3, 4, 5, 6, 7, 8, 9], 0)) // []
console.log(listChunk([1, 2, 3, 4, 5, 6, 7, 8, 9], -1)) // []
3、获取数组交集
const intersection = (list, ...args) => list.filter(item => args.every(list => list.includes(item)))
console.log(intersection([2, 1], [2, 3])) // [2]
console.log(intersection([1, 2], [3, 4])) // []
4、函数柯里化
const curring = fn => {
const { length } = fn
const curried = (...args) => {
return (args.length >= length
? fn(...args)
: (...args2) => curried(...args.concat(args2)))
}
return curried
}
const listMerge = (a, b, c) => [a, b, c]
const curried = curring(listMerge)
console.log(curried(1)(2)(3)) // [1, 2, 3]
console.log(curried(1, 2)(3)) // [1, 2, 3]
console.log(curried(1, 2, 3)) // [1, 2, 3]
5、字符串前面空格去除与替换
const trimStart = str => str.replace(new RegExp('^([\\s]*)(.*)$'), '$2')
console.log(trimStart(' abc ')) // abc
console.log(trimStart('123 ')) // 123
6、字符串后面空格去除与替换
const trimEnd = str => str.replace(new RegExp('^(.*?)([\\s]*)$'), '$1')
console.log(trimEnd(' abc ')) // abc
console.log(trimEnd('123 ')) // 123
7、获取当前子元素是其父元素下子元素的排位
const getIndex = el => {
if (!el) {
return -1
}
let index = 0
do {
index++
} while (el = el.previousElementSibling);
return index
}
8、获取当前元素相对于document的偏移量
const getOffset = el => {
const {
top,
left
} = el.getBoundingClientRect()
const {
scrollTop,
scrollLeft
} = document.body
return {
top: top + scrollTop,
left: left + scrollLeft
}
}
9、获取元素类型
const dataType = obj => Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase();
10、判断是否是移动端
const isMobile = () => 'ontouchstart' in window
11、fade动画
const fade = (el, type = 'in') {
el.style.opacity = (type === 'in' ? 0 : 1)
let last = +new Date()
const tick = () => {
const opacityValue = (type === 'in'
? (new Date() - last) / 400
: -(new Date() - last) / 400)
el.style.opacity = +el.style.opacity + opacityValue
last = +new Date()
if (type === 'in'
? (+el.style.opacity < 1)
: (+el.style.opacity > 0)) {
requestAnimationFrame(tick)
}
}
tick()
}
12、将指定格式的字符串解析为日期字符串
const dataPattern = (str, format = '-') => {
if (!str) {
return new Date()
}
const dateReg = new RegExp(`^(\\d{2})${format}(\\d{2})${format}(\\d{4})$`)
const [, month, day, year] = dateReg.exec(str)
return new Date(`${month}, ${day} ${year}`)
}
console.log(dataPattern('12-25-1995')) // Mon Dec 25 1995 00:00:00 GMT+0800 (中国标准时间)
13、禁止网页复制粘贴
const html = document.querySelector('html')
html.oncopy = () => false
html.onpaste = () => false
14、input框限制只能输入中文
const input = document.querySelector('input[type="text"]')
const clearText = target => {
const {
value
} = target
target.value = value.replace(/[^\u4e00-\u9fa5]/g, '')
}
input.onfocus = ({target}) => {
clearText(target)
}
input.onkeyup = ({target}) => {
clearText(target)
}
input.onblur = ({target}) => {
clearText(target)
}
input.oninput = ({target}) => {
clearText(target)
}
15、去除字符串中的html代码
const removehtml = (str = '') => str.replace(/<[\/\!]*[^<>]*>/ig, '')
console.log(removehtml('
哈哈哈哈<呵呵呵
')) // 哈哈哈哈<呵呵呵
评论
偷偷告诉你如何一台电脑开多个微信!
大家好,我是轩辕。前几天在粉丝群里,有人问我是怎么在一台电脑上同时登录两个微信的?正好之前写过一篇文章,分析过原理,分享给没看过的小伙伴学习一下。手机端多开微信估计很多人都知道,像华为、小米等手机系统都对此做了支持,不过在运行Windows系统的电脑上怎么启动两个微信呢?其实很简单,你只需要写一个批
编程技术宇宙
0
盘点Lombok的几个骚操作,你绝对没用过!
👉 欢迎加入小哈的星球 ,你将获得: 专属的项目实战 / Java 学习路线 / 一对一提问 / 学习打卡 / 赠书福利全栈前后端分离博客项目 2.0 版本完结啦, 演示链接:http://116.62.199.48/ ,新项目正在酝酿中
小哈学Java
0
堪称最优秀的Docker可视化管理工具——Portainer你真的会用吗?
来源:blog.csdn.net/shark_chili3007/article/details/123366179👉 欢迎加入小哈的星球 ,你将获得: 专属的项目实战 / Java 学习路线 / 一对一提问 / 学习打卡 / 赠书福利全栈前后端分离博客项目
小哈学Java
0
【深度学习】人人都能看懂的LSTM
熟悉深度学习的朋友知道,LSTM是一种RNN模型,可以方便地处理时间序列数据,在NLP等领域有广泛应用。在看了台大李宏毅教授的深度学习视频后,特别是介绍的第一部分RNN以及LSTM,整个人醍醐灌顶。本文就是对视频的记录加上了一些个人的思考。0. 从RNN说起循环神经网络(Recurrent Neur
机器学习初学者
0
测试新人,如何快速上手一个陌生的系统!
大家好,我是狂师!作为刚入行不久的测试新人,面对一个陌生的系统时,可能会感到有些手足无措。面对一个全新的系统系统,如何快速上手并展开有效的测试工作是一个重要的挑战。本文将探讨测试新人如何通过一系列步骤和策略,快速熟悉并掌握新系统的测试要点,从而提高测试效率和质量。本文旨在为测试新手提供一份指导,帮助
测试开发技术
0
如何计算数据中心的冷却需求?
今日分享 【导读】数据中心的冷却要求受多种因素影响,包括设备的热量输出、占地面积、设施设计和电气系统功率额定值等等……众所周知,环境因素会严重影响数据中心设备。过多的热量积聚会损坏服务器,可能导致其自动关闭。经常在高于可接受的温度下运行服务器会缩短其使用
数据中心运维管理
0
多人同时导出 Excel 干崩服务器!新来的阿里大佬给出的解决方案太优雅了!
点击关注公众号,Java 干货及时推送↓推荐阅读:面试辅导,我们出大成果了!来源:juejin.cn/post/7259249904777838629前言 业务诉求:考虑到数据库数据日渐增多,导出会有全量数据的导出,多人同时导出可以会对服务性能造成影响,导出涉及到mysql查询的io操作,
Java技术栈
1
知乎热议:博士生最好的状态是什么?
链接:https://www.zhihu.com/question/447412618编辑:深度学习与计算机视觉声明:仅做学术分享,侵删作者:JackieLeehttps://www.zhihu.com/question/447412618/answer/2963078772最好状态比较难说,最开心
机器学习初学者
0