JavaScript中提高效率的技巧一
1.生成随机颜色的两种方式
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)
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"
}
}
}
*/