Home > headlines > body text

11 surprising JavaScript One-Liners!

Release: 2021-12-06 15:15:26
forward
2812 people have browsed it

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.

11 surprising JavaScript One-Liners!

const characterCount = (str, char) => str.split(char).length - 1
Copy after login

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.

11 surprising JavaScript One-Liners!

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object
Copy after login

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:

11 surprising JavaScript One-Liners!##

const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
Copy after login

In the wait one-liner, we Create a promise and resolve it after a given time using the setTimeout function.

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.

11 surprising JavaScript One-Liners!

const daysBetween = (date1, date2) => Math.ceil(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24))
Copy after login

The logic behind this one-liner is easy to understand. When two dates are subtracted, the return value is the difference in milliseconds. To convert milliseconds to days we have to divide it by milliseconds, seconds, minutes and hours respectively.

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.

11 surprising JavaScript One-Liners!

const redirect = url => location.href = url
Copy after login

location is a method on the global window object. Setting the href attribute behaves the same as when the user clicks on the link.

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.

11 surprising JavaScript One-Liners!

const touchSupported = () => ('ontouchstart' in window || DocumentTouch && document instanceof DocumentTouch)
Copy after login

In this line we are checking if the document supports touchstart event.

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.

11 surprising JavaScript One-Liners!

const insertHTMLAfter = (html, el) => el.insertAdjacentHTML('afterend', html)
Copy after login

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:

11 surprising JavaScript One-Liners!

const shuffle = arr => arr.sort(() => 0.5 - Math.random())
Copy after login

它利用数组的排序方法,在数组的前一个元素之前或之后进行随机排序。

9、在网页上获取选定的文本

浏览器在全局 windows 对象上有一个名为 getSelection 的内置方法。

使用此方法,你可以创建一个单行,返回网页上突出显示或选定的文本。

11 surprising JavaScript One-Liners!

const getSelectedText = () => window.getSelection().toString()
Copy after login

10、 获取一个随机布尔值

在编程时,尤其是在编写游戏时,有时你会想要随机采取行动。在这种情况下,下面的单行非常方便。

11 surprising JavaScript One-Liners!

const getRandomBoolean = () => Math.random() >= 0.5
Copy after login

上面的单行有 50/50 的机会返回 true 或 false。因为生成的随机数大于 0.5 的概率等于较小的概率。

但是,例如,如果你想获得一个概率为 70% 错误的随机布尔值,那么,你可以简单地将 0.5 更改为 0.7,依此类推。

11、计算数组的平均值

可以使用多种方法计算数组的平均值。但道理对所有人都是一样的。你必须获得数组及其长度的总和;然后除法给出平均值。

11 surprising JavaScript One-Liners!

const average = (arr) => arr.reduce((a, b) => a + b) / arr.length
Copy after login

在平均单行中,我们使用 reduce 来获取一行中的数组的总和,而不是使用循环。然后,我们将其除以数组长度,这是数组的平均值。

写在最后

今天的内容,就是这样,现在,我想你已经了解了 11 个简单但功能强大的 JavaScript 单行程序。我试着选择那些不是很受欢迎和知名度的东西,这样你就可以学习新东西。我每天都在使用它们,我想对你也会有所帮助。

感谢你的阅读,如果你喜欢它,一定要点赞,如果你对这篇文章有什么想说的,请在留言区告诉我们。

翻译: 杨小二

英文:

https://betterprogramming.pub/11-rare-javascript-one-liners-that-will-amaze-you-331659832301

Related labels:
source:Web前端开发
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template