11 种有用的 JavaScript 技巧

JavaScript11个月前发布 admin
1,760 0

今天这篇文章,我想与你分享 11个有用JavaScript技巧,这些技巧可以大大提高你的工作效率。

1、生成随机颜色的两种方式

1).generateRandomHexColor

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)

2、复制内容到剪贴板的两种方式

方式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’)

3.获取URL中的查询参数

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

4.Please wait for a while

const timeout = (timeout) => new Promise((rs) => setTimeout(rs, timeout))

5.打乱数组

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]

6.深拷贝一个对象

如何深拷贝一个对象?使用 structuredClone 使它变得非常容易。

const obj = {
name: ‘fatfish’,
node: {
name: ‘medium’,
node: {
name: ‘blog’
}
}
}

const cloneObj = 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”
}
}
}
*/

7.确保一个元素在可见区域内

前段时间在工作中遇到了一个很麻烦的需求,感谢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

8.获取当前选中的文本

许多翻译网站都有此功能,可以在其中选择一段文字并将其翻译成其他国家/地区的语言。

const getSelectedContent = () => window.getSelection().toString()

9.获取所有浏览器cookie

可以很方便的帮我们获取浏览器中的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”
}
*/

10.删除指定名称的cookie

我们只能删除没有 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

11.将多维数组转换为一维数组

虽然我们通过递归函数将多维数组转换为一维数组,但是有一个非常简单的方法可以解决这个问题。

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]

总结

以上就是我今天想与你分享的全部内容,希望这些内容能够对你有所帮助。

最后,感谢你的阅读。

© 版权声明

相关文章

暂无评论

暂无评论...