7 Killer JS Lines of Code

JavaScript is the most critical pillar of web development.

This post contains code snippets hand-picked by sterile gloves and placed on a satin pillow.
A team of 50 people reviewed the code and made sure it was in a highly polished state before release. Our article publishing expert from Switzerland lit a candle and the crowd booed as he entered the code into the best gold-encrusted keyboard money can buy.
We all had a wonderful celebration with the whole party marching down the street to the cafe and the whole town of Kolkata waving "Good luck!" as the article was posted online.

Happy reading!

array out of order

When working with algorithms that require some level of randomization, you will often find that shuffling arrays is a fairly necessary skill. The following snippet shuffles an array in-place with O(n log n) complexity.

const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5) 。
// 测试
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(shuffleArray(arr))。

copy to clipboard

In web applications, copy-to-clipboard is rapidly gaining popularity due to its convenience to the user.

const copyToClipboard = (text) =>
  navigator.clipboard?.writeText && navigator.clipboard.writeText(text)。
// 测试
copyToClipboard("Hello World!")。

Note: According to caniuse, this method works for 93.08% of global users. So it must be checked whether the user's browser supports the API. To support all users, you can use one input and copy its content.

Array deduplication

Each language has its own implementation of a hash list, in JavaScript it's called a Set. You can easily get unique elements from an array using the Set data structure.

const getUnique = (arr) => [...new Set(arr)]。
// 测试
const arr = [1, 1, 2, 3, 3, 4, 4, 5, 5];
console.log(getUnique(arr))。

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 device. Fortunately, media queries can be leveraged to make this task easy.

const isDarkMode = () =>
  window.matchMedia &&
  window.matchMedia("(prefers-color-scheme: dark)").matches。
// 测试
console.log(isDarkMode())。

According to caniuse, matchMedia has a 97.19% approval rating.

scroll to top

Beginners often find themselves struggling with scrolling elements correctly. The easiest way to scroll an element is to use the scrollIntoView method. Add behavior. "smooth" for smooth scrolling animations.

const scrollToTop = (element) =>
  element.scrollIntoView({ behavior: "smooth", block: "start" })。

scroll to bottom

Just like scrollToTop method, scrollToBottom method can also be easily implemented with scrollIntoView method, just switch the block value to end

const scrollToBottom = (element) =>
  element.scrollIntoView({ behavior: "smooth", block: "end" })。

Generate random colors

Does your application rely on random color generation? Look no further, the following code snippet will do what you want

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

Follow me for weekly news in tech
Need a top rated front-end development freelancer to solve your development problems? Please contact me on Upwork
Want to see what I'm doing? Please check out my personal website and GitHub
Want to contact me? Please connect with me on LinkedIn
I am a freelancer and will start as a digital nomad in mid-2022. Want to know about my journey? Follow me on Instagram

Github 是 [链接]

4.2k 声望
441 粉丝
0 条评论
推荐阅读
从 JavaScript 迁移到 TypeScript
我作为一名 JavaScript 开发人员已经很多年了,我并没有太多打算跳出我的技术堆栈。我告诉自己,坚持你已经知道的东西和尝试学习太多的编程语言可能会让人望而生畏。

chatgpt1阅读 1.6k

安全地在前后端之间传输数据 - 「3」真的安全吗?
在「2」注册和登录示例中,我们通过非对称加密算法实现了浏览器和 Web 服务器之间的安全传输。看起来一切都很美好,但是危险就在哪里,有些人发现了,有些人嗅到了,更多人却浑然不知。就像是给门上了把好锁,还...

边城31阅读 7.2k评论 5

封面图
涨姿势了,有意思的气泡 Loading 效果
今日,群友提问,如何实现这么一个 Loading 效果:这个确实有点意思,但是这是 CSS 能够完成的?没错,这个效果中的核心气泡效果,其实借助 CSS 中的滤镜,能够比较轻松的实现,就是所需的元素可能多点。参考我们...

chokcoco20阅读 2.1k评论 2

在前端使用 JS 进行分类汇总
最近遇到一些同学在问 JS 中进行数据统计的问题。虽然数据统计一般会在数据库中进行,但是后端遇到需要使用程序来进行统计的情况也非常多。.NET 就为了对内存数据和数据库数据进行统一地数据处理,发明了 LINQ (L...

边城17阅读 1.9k

封面图
【已结束】SegmentFault 思否写作挑战赛!
SegmentFault 思否写作挑战赛 是思否社区新上线的系列社区活动在 2 月 8 日 正式面向社区所有用户开启;挑战赛中包含多个可供作者选择的热门技术方向,根据挑战难度分为多个等级,快来参与挑战,向更好的自己前进!

SegmentFault思否20阅读 5.6k评论 10

封面图
过滤/筛选树节点
又是树,是我跟树杠上了吗?—— 不,是树的问题太多了!🔗 相关文章推荐:使用递归遍历并转换树形数据(以 TypeScript 为例)从列表生成树 (JavaScript/TypeScript) 过滤和筛选是一个意思,都是 filter。对于列表来...

边城18阅读 7.7k评论 3

封面图
你可能不需要JS!CSS实现一个计时器
CSS现在可不仅仅只是改一个颜色这么简单,还可以做很多交互,比如做一个功能齐全的计时器?样式上并不复杂,主要是几个交互的地方数字时钟的变化开始、暂停操作重置操作如何仅使用 CSS 来实现这样的功能呢?一起...

XboxYan21阅读 1.6k评论 1

封面图

Github 是 [链接]

4.2k 声望
441 粉丝
宣传栏