 
今天这篇文章,我想与你分享 11个有用的JavaScript功能,它们将极大地提高我们的工作效率。
1.生成随机颜色的两种方式
1).生成RandomHexColor
const generateRandomHexColor = () => {  return `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')}`}
generateRandomHexColor() // #a8277cgenerateRandomHexColor() // #09c20cgenerateRandomHexColor() // #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=100parseQuery('name') // fatfishparseQuery('age') // 100parseQuery('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]
以上就是我今天想与你分享的11个有用的技巧,希望对你有所帮助。
该文章在 2024/10/14 11:05:48 编辑过