数组去重
应用ES6中提供的Set数据结构
const arr = [1, 2, 3, 4, 3, 2, 1]const newArr = [...new Set(arr)]// 或const newArr = Array.from(new Set(arr))console.log(newArr)
应用数组中的reduce办法
const arr = [1, 2, 3, 4, 3, 2, 1]const newArr = arr.reduce((result, item) => { if (!result.includes(item)) { result.push(item) } return result}, [])console.log(newArr)
变量替换
假如当初有a,b两个变量,在不依赖于长期变量的状况下,如何疾速的实现变量之间的值替换呢?
解构赋值
let a = 1let b = 2[a, b] = [b, a]console.log(a, b) // a --> 2, b --> 1
位异或
let a = 1let b = 2// 应用位异或运算a = a ^ bb = b ^ aa = a ^ b// 或间接替换a = a + bb = a - ba = a - bconsole.log(a, b) // a --> 2, b --> 1
借用数组
let a = 1let b = 2b = [a, a = b][0]console.log(a, b) // a --> 2, b --> 1
字符串分组
将字符转以特定的字符进行分组, 比方依照空格,逗号,分号字符进行分组
const str = 'a b,c;d,e f,cf'const result = str.match(/[^\s,;]+/g)// result -> ["a", "b", "c", "d", "e", "f", "cf"]
随机字符串
利用Math.random()生成随机数字,而后再通过tostring办法将其转换为随机字符串
const str = Math.random().toString(36).substr(2)console.log(str) // --> "3mknchm44dt"
明码强度判断
判断规定:
- 长度必须大于6
- 蕴含数字,明码强度+1
- 蕴含大/小写字母,明码强度+1
- 蕴含除数字和大小写字母外的其余字符,明码强度+1
function getStrength(str) { let strength = 0 if (str && str.length >= 6) { if (/\d+/.test(str)) { ++strength } if (/[a-zA-Z]+/.test(str)) { ++strength } if (/[^0-9a-zA-Z]+/.test(str)) { ++strength } } return strength}
首字母大写
应用CSS
.text { text-transform: capitalize;}
应用JS
const upperCase = data => { if (data) { const [first, ...char] = data return first.toUpperCase() + char.join('') } return ''}console.log(upperCase('hello'))
这里用到了字符串的解构赋值,行将第一个字母赋值给first,其余字母赋值到char中,从而实现将首字母转换为大写。
链判断运算符
在开发中,如果须要读取对象外部的某个属性,往往须要判断该对象是否存在。比方,须要获取result.userInfo.username中的username,为了防止js报错,个别的写法为:
const { username } = result.userInfo || {}// 或const username = result.userInfo ? result.userInfo.username : ''
这样,每一层对象的属性都必须判断是否存在,对象层级关系较大,则写法更加简单。好在ES2020 为咱们提供了链判断运算符(?.
),上述的代码能够简化为
const username = result?.userInfo?.username// 等同于const username = result && result.userInfo ? result.userInfo.username : undefinedconst name = form.querySelector('input')?.value// 等同于const name = form.querySelector('input') ? form.querySelector('input').value : undefined
链判断运算符也能够判断办法是否存在
actions?.getuserInfo?.()// 等同于actions && actions.getUserInfo ? actions.getUserInfo() : undefined
然而,在古代浏览器中,还不反对这种写法,所以咱们必须借助babel将它本义为古代浏览器可辨认的代码。
- 装置依赖
yarn add -D @babel/plugin-proposal-optional-chaining
- 在.babelrc中进行配置
{ "presets": ["@babel/preset-env"], "plugins": [ "@babel/plugin-proposal-optional-chaining" ]}
接下来就能够欢快的应用链判断运算符啦!
复制内容到剪切板
复制任何内容到剪切板,并返回一个promise
function setStyle (el, styleName, value) { if (el && styleName) { if (typeof styleName == 'object') { for (let key in styleName) { setStyle(el, key, styleName[key]) } } else { el.style[styleName] = value } }}function copyText(value) { return new Promise((resolve, reject) => { const el = document.createElement('input') el.setAttribute('readonly', 'readonly') setStyle(el, { fontSize: '12px', border: 0, outline: 0, margin: 0, padding: 0, position: 'fixed', top: 0, left: '-9999px', zIndex: -10 }) el.value = value document.body.appendChild(el) el.select() el.setSelectionRange(0, String(value).length) if (document.execCommand('Copy')) { resolve(value) } else { reject(new Error('Copy failed')) } setTimeout(() => { el.remove() }, 3000) })}copyText('hello world') .then(() => console.log('success')) .catch(e => console.log(e.message))
防抖和节流
防抖
概念:防抖的作用在于,如果某个事件或函数在某个时间段内间断触发,那么只有最初一次触发,事件回调或函数才会被真正的调用。如浏览器的resize, scroll, mousemove等事件。在短时间内会被屡次触发,如果不加以限度,不仅节约客户端资源,还有可能造成客户端卡顿,卡死以及解体。如果有网络申请,短时间内大量的网络申请还会造成网络梗塞(因为浏览器的限度,个别浏览器只能同时解决6个左右的申请,当申请过多时,只有等申请队列中的申请都实现后,才会开始下一个申请,否则排队中的申请始终处于期待状态,无奈被解决)以及减少服务器压力。
function debounce(fn, timeout = 500) { // 这里通过闭包使timer变量不会被JS垃圾回收机制回收,从而常驻内存中 let timer = null return function(...args) { if (!timer) { timer = setTimeout(() => { fn.apply(this, args) timer = null }, timeout) } }}// 这里将函数通过节流函数封装后返回`fn`const fn = debounce(() => console.log('debounce'))
节流
概念:顾名思义,节流的意义在于限度其流入/流出量。通常用在当一个事件或函数在某个工夫内间断触发或调用时,在肯定时间段内,只调用一次事件处理函数。如某个事件在特定的状况下,20秒内触发了50次,每次都会向服务器发送数据申请,通过节流限度其执行次数,即1s内只容许其执行1次,这样大大的缩小了申请数量,加重服务器压力的同时,也缩小了客户端的内存开销,防止了呈现内存透露。
function throttle(fn, delay = 1000) { let last = 0 return function(...args) { const current = Date.now() if (current - last > delay) { fn.apply(this, args) last = current } }}
一言以蔽之,防抖函数的作用在于在特定工夫内间断触发的事件,只有最初一次会被执行。节流函数的作用在于,在固定工夫内间断被触发的事件在n秒内只能被触发执行一次。
及时获取更新,理解更多动静,请关注 https://www.gogoing.site
如果你感觉这篇文章对你有帮忙,欢送关注微信公众号-前端学堂,更多精彩文章等着你!