11 Useful JavaScript Tips to Boost Your Efficiency

This article presents 11 practical JavaScript tips to boost efficiency, covering random color generation, clipboard operations, URL query retrieval, timeout handling, array shuffling, deep object copying, and more. These tips aim to enhance coding productivity.

主页 > 博客 > 11 Useful JavaScript Tips to Boost Your Efficiency

Today, in this article, I want to share with you 11 useful JavaScript tips that will greatly enhance your work efficiency.

11 Useful JavaScript Tips to Boost Your Efficiency

1. Generate Random Colors

1.1 Generate Random Hex Color

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

generateRandomHexColor(); // #a8277c
generateRandomHexColor(); // #09c20c
generateRandomHexColor(); // #dbc319

1.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. Copy Content to Clipboard

2.1 Using Navigator Clipboard API

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

2.2 Using Dynamic Textarea

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 Query Parameters from URL

const parseQuery = (name) => {
  return new URL(window.location.href).searchParams.get(name);
};

// Example: https://medium.com?name=fatfish&age=100
parseQuery('name'); // fatfish
parseQuery('age'); // 100
parseQuery('sex'); // null

4. Wait for a While

const timeout = (timeout) => new Promise((resolve) => setTimeout(resolve, timeout));

5. Shuffle an 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

// Using 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);

// Original object remains unchanged
console.log(obj);

7. Ensure Element is in Viewport

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 Currently Selected Text

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

9. Get All Browser Cookies

const getAllCookies = () => {
  return document.cookie.split(";").reduce(function(cookieObj, cookie) {
    const cookieParts = cookie.split("=");
    cookieObj[cookieParts[0].trim()] = cookieParts[1].trim();
    return cookieObj;
  }, {});
};

// Example output
/*
{
  "_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"
}
*/
getAllCookies();
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. Flatten a Multidimensional Array

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]

// Using Array flat method
console.log(arr.flat(Infinity)); // [1, 2, 3, 4, 5, 6]

Conclusion

These are the 11 useful tips I wanted to share with you today. I hope they prove helpful to you. Thank you for reading till the end, happy coding!

Article Link:https://jsnoteclub.com/blog/11-useful-javascript-tips-to-boost-your-efficiency/
JsNoteClub:Share interesting and useful JavaScript tools and tips.

除非注明,否则均为 jsnoteclub.com 原创文章,请勿转载谢谢!

本文标题:11 Useful JavaScript Tips to Boost Your Efficiency

本文链接:https://jsnoteclub.com/blog/11-useful-javascript-tips-to-boost-your-efficiency/