JavaScript is a very complex language, and many novices will find many functions difficult to use when developing applications using it. With the 36 JavaScript tips I have summarized according to their functions, copy and paste can be done with one click!
Help you improve development efficiency, solve problems quickly, get off work early, and catch fish early!
DOM-related
1. Detect if an element is focused
const hasFocus = el => el === document.activeElement
2. Get all sibling elements of an element
const a = el => [].slice.call(el.parentNode.children).filter(child => child !== el)
3. Get the currently selected text
const getSelectedText = () => window.getSelection().toString()
4. Return to the previous page
const goBack = () => history.go(-1)
5. Get all cookies and convert them to objects
const getCookies = () => document.cookie
.split(';')
.map(item => item.split('='))
.reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] =v) && acc, {})
6. Clear all cookies
const clearCookies = () => document.cookie
.split(';')
.forEach(c => document.cookie = c.splace(/^+/, '')
.replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`))
)
7. Convert URL parameters to objects
const getUrlParams = (query) =>Array.from(new URLSearchParams(query)).reduce((p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),{});
8. Detect whether it is dark mode
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
Array related
9. Compare two arrays
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
10. Convert array to object
const arrayToObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});
11. Count the array by attribute
const countBy = (arr, prop) => arr.reduce((prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev), {} );
12. Determine whether the array is not empty
const arrayIsNotEmpty = (arr) => Array.isArray(arr) && Object.keys(arr).length > 0;
13. Expand multidimensional array
const flat_entries = arr => [].concat(...arr);
14. Get the last element of the array
const lastItem = arr => arr.slice(-1)[0]
object related
15. Check if multiple objects are equal
const isEqual = (...objects) => objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0]));
16. Extract property value from object array
const pluck = (objs, property) => objs.map((obj) => obj[property]);
17. Reverse the key value of an object
const invert = (obj) => Object.keys(obj).reduce((res, k) => Object.assign(res, { [obj[k]]: k }), {});
18. Remove null and undefined properties from objects
const removeNullAndUndefined = (obj) =>
Object.entries(obj)
.reduce((a, [k, v]) => (v == null ? a : ((a[k] = v), a)), {});
19. Sort objects by their properties
const sort = (obj) => Object
.keys(obj)
.sort()
.reduce((p, c) => ((p[c] = obj[c]), p), {});
20. Check if an object is an array
const isArray = (obj) => Array.isArray(obj);
21. Check if the object is a Promise
const isPromise = (obj) =>
!!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
22. Swap two objects
const exchange = (a, b) => [a, b] = [b, a]
string correlation
23. Check if the path is relative
const isRelative = (path) => !/^([az]+:)?[\\/]/i.test(path);
24. Lowercase the first character of a string
const lowercaseFirst = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;
25. Repeat a string
const repeat = (str, numberOfTimes) => str.repeat(numberOfTimes);
26. Generate IP address
const randomIp = () => Array(4).fill(0)
.map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0) )
.join('.');
27. Generate hexadecimal color string
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;
28. Generate rgb color string
const randomRgbColor = () => `rgb(${Math.floor(Math.random()*255)}, ${Math.floor(Math.random()*255)}, ${Math.floor(Math.random()*255)})`
29. Underscore to camelCase
const toHump = str => str.replace(/\_(\w)/g, (all, letter) => letter.toUpperCase());
30. CamelCase to underscore
const toLine = str => str.replace(/([A-Z])/g,"_$1").toLowerCase()
31. Check if a string is a hex color
const isHexColor = (color) => /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color);
32. RGB string to hexadecimal string
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1) ;
date related
33. The number of days between two dates
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
34. Check if date is valid
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
other
35. Detect if code is in Node.js environment
const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
36. Detect whether the code is in the browser environment
const isBrowser = typeof window === 'object' && typeof document === 'object';
If you also have some commonly used functions, or some functions in the article have a better implementation, you can also add them!