Share 11 useful JavaScript tips

e767293a5c22029e480562c8403ac70a.jpeg

In this article today, I want to share with you 11 useful JavaScript tips that will greatly improve your work efficiency.

1. Two ways to generate random colors

1).Generate RandomHexColor

const generateRandomHexColor = () => {
  return `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')}`
}
generateRandomHexColor() // #a8277c
generateRandomHexColor() // #09c20c
generateRandomHexColor() // #dbc319

2).Generate random 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. Two ways to copy content to the clipboard

Way 1

const copyToClipboard = (text) => navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.writeText(text)
copyToClipboard('hello medium')

Way 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. Get the query parameters in the 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. Scramble the array

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. Deep copy an object

How to deep copy an object? Using StructuredClone makes it very easy.

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. Make sure the element is within the visible area

Some time ago, I encountered a very troublesome need at work. Thanks to IntersectionObserver, I could easily detect whether an element was within the visible area.

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. Get the currently selected text

Many translation websites have this feature where you can select text and translate it into another country's language.

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

9. Get all browser cookies

Very convenient to help us obtain cookie information in the browser

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. Delete the cookie with the specified name

My friends, we can only delete cookies without HttpOnly flag.

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. Convert multi-dimensional array to one-dimensional array

Although, we convert a multi-dimensional array into a one-dimensional array through a recursive function, there is a very simple way to solve this problem.

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]

The secret is to use the flattening method of arrays.

const arr = [
  1,
  [
    2,
    [
      3,
      [
        4,
        [
          5,
          [
            6
          ]
        ]
      ]
    ]
  ]
]
console.log(arr.flat(Infinity)) // [1, 2, 3, 4, 5, 6]

Summarize

The above are 11 useful tips that I want to share with you today. I hope they will be helpful to you.

Thanks for reading until the end, and happy programming!

Learn more skills

Please click on the public account below

c250780fe10a41dafa6bb68d42f5c27c.gif

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/134873846