1. Array disordered
When using algorithms that require some degree of randomization, you will often find that shuffling arrays is a pretty necessary skill. The following fragment shuffles an array in-place with the complexity of O(n log n).
const shuffleArray = (arr) => (() => () - 0.5) // testconst arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; (shuffleArray(arr))
2. Copy to the clipboard
existWeb
In applications, copying to clipboard has become popular quickly because of its convenience to users.
const copyToClipboard = (text) => ?.writeText && (text) // testcopyToClipboard("Hello World!")
Notice:according tocaniuse
, This method is effective for 93.08% of global users. So you have to check whether the user's browser supports this API. To support all users, you can use one input and copy its contents.
3. Deduplication of array
Each language has its own hash list implementation, inJavaScript
In, it is called Set. You can easily get unique elements from an array using Set data structures.
const getUnique = (arr) => [...new Set(arr)] // testconst arr = [1, 1, 2, 3, 3, 4, 4, 5, 5]; (getUnique(arr))
4. Detect dark mode
With the popularity of dark mode, it is ideal to switch your app to dark mode if users have dark mode enabled in their devices. Fortunately, media queries can be used to make this task simple.
const isDarkMode = () => && ("(prefers-color-scheme: dark)").matches // test(isDarkMode())
according tocaniuse
data,matchMedia
The approval rating is 97.19%.
5. Scroll to the top
Beginners often find themselves having difficulties in scrolling elements correctly. The easiest way to scroll elements is to usescrollIntoView
method. Add behavior. "smooth
"To implement smooth scrolling animation.
const scrollToTop = (element) => ({ behavior: "smooth", block: "start" })
6. Scroll to the bottom
Just likescrollToTop
The same method,scrollToBottom
Methods can also be usedscrollIntoView
The method is easy to implement, just switch the block value to end
const scrollToBottom = (element) => ({ behavior: "smooth", block: "end" })
7. Generate random colors
Does your application rely on the generation of random colors? No need to read it anymore, the following code snippet can meet your requirements
const generateRandomHexColor = () => `#${(() * 0xffffff) .toString(16)}`;
This is all about this article about 7 killer JS tips. For more related JS tips, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!