今天这篇文章,我想与你分享 11个有用的JavaScript实用小技巧,它们将极大地提高你的工作效率。
1).生成RandomHexColor
const generateRandomHexColor = () => {
return `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')}`
}
generateRandomHexColor() // #a8277c
generateRandomHexColor() // #09c20c
generateRandomHexColor() // #dbc319
2).生成随机RGBA
const generateRandomRGBA = () => {
const r = Math.floor(Math.random() * 256)
const g = Math.floor(Math.random() * 256)
const b = Math.floor(Math.random() * 256)
const a = Math.random().toFixed(2)
return `rgba(${[ r, g, b, a ].join(',')})`
}
generateRandomRGBA() // rgba(242,183,70,0.21)
generateRandomRGBA() // rgba(65,171,97,0.72)
generateRandomRGBA() // rgba(241,74,149,0.33)
方式1
const copyToClipboard = (text) => navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.writeText(text)
copyToClipboard('hello medium')
方式2
const copyToClipboard = (content) => {
const textarea = document.createElement("textarea")
textarea.value = content
document.body.appendChild(textarea)
textarea.select()
document.execCommand("Copy")
textarea.remove()
}
copyToClipboard('hello medium')
const parseQuery = (name) => {
return new URL(window.location.href).searchParams.get(name)
}
// https://medium.com?name=fatfish&age=100
parseQuery('name') // fatfish
parseQuery('age') // 100
parseQuery('sex') // null
const timeout = (timeout) => new Promise((rs) => setTimeout(rs, timeout))
const shuffle = (array) => array.sort(() => 0.5 - Math.random())
shuffle([ 1, -1, 2, 3, 0, -4 ]) // [2, -1, -4, 1, 3, 0]
shuffle([ 1, -1, 2, 3, 0, -4 ]) // [3, 2, -1, -4, 0, 1]
如何深拷贝对象?使用 StructuredClone 使其变得非常容易。
之前写过一篇相关文章可以看看:https://blog.csdn.net/weixin_42333548/article/details/135197481?spm=1001.2014.3001.5501
const obj = {
name: 'fatfish',
node: {
name: 'medium',
node: {
name: 'blog'
}
}
}
const cloneObj = window.structuredClone(obj)
cloneObj.name = '1111'
cloneObj.node.name = '22222'
console.log(cloneObj)
/*
{
"name": "1111",
"node": {
"name": "22222",
"node": {
"name": "blog"
}
}
}
*/
console.log(obj)
/*
{
"name": "fatfish",
"node": {
"name": "medium",
"node": {
"name": "blog"
}
}
}
*/
前段时间,我在工作中遇到了一个非常麻烦的需求,感谢IntersectionObserver,我可以轻松检测某个元素是否在可见区域内。
const isElInViewport = (el) => {
return new Promise(function(resolve) {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.target === el) {
resolve(entry.isIntersecting)
}
})
})
observer.observe(el)
})
}
const inView = await isElInViewport(document.body)
console.log(inView) // true
许多翻译网站都有此功能,你可以选择文本并将其翻译成另一个国家的语言。
const getSelectedContent = () => window.getSelection().toString()
非常方便的帮助我们获取浏览器中的cookie信息
const getAllCookies = () => {
return document.cookie.split(";").reduce(function(cookieObj, cookie) {
const cookieParts = cookie.split("=")
cookieObj[cookieParts[0].trim()] = cookieParts[1].trim()
return cookieObj
}, {})
}
getAllCookies()
/*
{
"_ga": "GA1.2.496117981.1644504126",
"lightstep_guid/medium-web": "bca615c0c0287eaa",
"tz": "-480",
"nonce": "uNIhvQRF",
"OUTFOX_SEARCH_USER_ID_NCOO": "989240404.2375598",
"sz": "2560",
"pr": "1",
"_dd_s": "rum"
}
*/
我的朋友,我们只能删除没有 HttpOnly 标志的 cookie。
const clearCookie = (name) => {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
clearCookie('_ga') // _ga is removed from the cookie
虽然,我们通过递归函数将多维数组转换为一维数组,但是有一个非常简单的方法可以解决这个问题。
const flatten = (array) => {
return array.reduce((result, it) => {
return result.concat(Array.isArray(it) ? flatten(it) : it)
}, [])
}
const arr = [
1,
[
2,
[
3,
[
4,
[
5,
[
6
]
]
]
]
]
]
console.log(flatten(arr)) // [1, 2, 3, 4, 5, 6]
秘诀就是使用数组的扁平化方法。
const arr = [
1,
[
2,
[
3,
[
4,
[
5,
[
6
]
]
]
]
]
]
console.log(arr.flat(Infinity)) // [1, 2, 3, 4, 5, 6]
总结
以上就是我今天想与你分享的11个有用的技巧,希望对你有所帮助。
添加好友备注【进阶学习】拉你进技术交流群
?