11 surprising JavaScript One-Liners!
What do you do if you want to impress professional developers? It's simple: use simple logic and as little code as possible to solve a complex problem. With the introduction of ES6 arrow functions, it is possible to create single lines of code that look elegant and simple.
In this article, I will share with you 11 rare but powerful one-liners. are you ready? Let's start with the first one!
1. Get the number of characters in a string
Get the number of characters is a useful utility that can be useful in many situations. You can use this to get the number of spaces followed by the number of words, or this can be used to get the count of a certain delimiter in a string.
const characterCount = (str, char) => str.split(char).length - 1
The idea is very simple. We split the string using the passed argument char and get the length of the returned array. Because each time the string is split, there are one more strings than the splitter; so subtracting 1, we have a characterCount single line.
2. Check whether the object is empty
Checking the emptyness of an object is actually much more difficult than it seems. Every check to see if an object is equal to {} returns false, even if the object is empty.
Luckily, the following single line of code does exactly what we want.
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object
In this line, we check whether the length of the object's key is equal to 0, and whether the passed parameter is an actual object.
3. Wait for a certain period of time and then execute
In this single line of code, we will be exposed to some asynchronous programming. The idea is simple.
When running the code, if you want to wait for a certain amount of time, here is the wait one-liner:
##
const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
4. Get the day difference between two dates
When developing web applications, dates are often the most confusing part because there are many concepts that are very confusing. Easily miscalculated. This is a powerful one-liner to calculate the difference in days between two dates. But there is more to do. Like me, you can create your own single lines to calculate monthly, yearly differences, etc.const daysBetween = (date1, date2) => Math.ceil(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24))
5. Redirect to another URL
If you’ve ever created a real website, I’m sure you’ve encountered authentication logic. For example, non-admin users should not be able to access the /admin route. If the user tries, then, you must redirect them to another URL. This one-liner works just fine for the situation I mentioned above, but I think you can find many more use cases.const redirect = url => location.href = url
6. Check the touch support on your device
As more and more devices can connect to the Internet, the need to create responsive websites becomes more and more important. high. Twenty years ago, developers would have considered a desktop version of their website, but today more than 50% of web traffic comes from touch devices. So taking some action based on a device's touch support is such an important concept.const touchSupported = () => ('ontouchstart' in window || DocumentTouch && document instanceof DocumentTouch)
7. Insert a string of HTML after the element
When developing web applications, it is very common to use JavaScript to update the DOM. There are some basic ways to get the job done, but when things get complicated, it can be difficult to overcome. This is a single line of code that injects a string of HTML immediately after the HTML element. With a few minutes of thinking and googling, I'm sure you can find a previous version of this one-liner.const insertHTMLAfter = (html, el) => el.insertAdjacentHTML('afterend', html)
8. Shuffling an arrayShuffling a set of data during development is a common situation you may encounter at any time. Unfortunately, JavaScript There is no built-in shuffling method for arrays. But, here's a shuffle one-liner you can use every day:
const shuffle = arr => arr.sort(() => 0.5 - Math.random())
它利用数组的排序方法,在数组的前一个元素之前或之后进行随机排序。
9、在网页上获取选定的文本
浏览器在全局 windows 对象上有一个名为 getSelection 的内置方法。
使用此方法,你可以创建一个单行,返回网页上突出显示或选定的文本。
const getSelectedText = () => window.getSelection().toString()
10、 获取一个随机布尔值
在编程时,尤其是在编写游戏时,有时你会想要随机采取行动。在这种情况下,下面的单行非常方便。
const getRandomBoolean = () => Math.random() >= 0.5
上面的单行有 50/50 的机会返回 true 或 false。因为生成的随机数大于 0.5 的概率等于较小的概率。
但是,例如,如果你想获得一个概率为 70% 错误的随机布尔值,那么,你可以简单地将 0.5 更改为 0.7,依此类推。
11、计算数组的平均值
可以使用多种方法计算数组的平均值。但道理对所有人都是一样的。你必须获得数组及其长度的总和;然后除法给出平均值。
const average = (arr) => arr.reduce((a, b) => a + b) / arr.length
在平均单行中,我们使用 reduce 来获取一行中的数组的总和,而不是使用循环。然后,我们将其除以数组长度,这是数组的平均值。
写在最后
今天的内容,就是这样,现在,我想你已经了解了 11 个简单但功能强大的 JavaScript 单行程序。我试着选择那些不是很受欢迎和知名度的东西,这样你就可以学习新东西。我每天都在使用它们,我想对你也会有所帮助。
感谢你的阅读,如果你喜欢它,一定要点赞,如果你对这篇文章有什么想说的,请在留言区告诉我们。
翻译: 杨小二
英文:
https://betterprogramming.pub/11-rare-javascript-one-liners-that-will-amaze-you-331659832301

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data