当前位置:网站首页>Share 25 useful JS single line codes
Share 25 useful JS single line codes
2022-07-25 19:48:00 【Front end talent】

english | https://medium.com/@daaaan
Translation arrangement | web The front-end development (ID:web_qdkf)
JavaScript There are many practical examples of single line code , They can do many powerful things , No matter you are JavaScript Novice or experienced developers , It's always good to learn something new .
In today's article , We will share some JavaScript Single line code , I hope it can help you solve some problems encountered in daily development JavaScript problem , I hope there are some single line codes in this list that you don't know yet , I also hope you can learn oneortwo skills !
Let's start now .
1、 Generate a range of random numbers
Use Math.random() Functions can easily be used in JavaScript Get random values from . But what about random numbers in a certain range ? There is no standard JavaScript function . The following function can be used to solve this problem .
Please note that , The maximum value is included in the range , If you want to exclude the maximum value from the range , You can delete + 1.
const randomNumberInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;2、 Toggle Boolean
Switching Boolean values is one of the oldest techniques in all programming books . A very basic programming problem , It can be solved in many different ways . Instead of using if Statement to determine what value the Boolean value is set to , Let's use the following function —— in my opinion , This is the simplest way .
const toggle = (value) => value = !value3、 Random sorting of array elements
have access to Math.random() Function sorts the array elements in random order . This is a common question . however , This sort should not be used to achieve complete randomness , Should not be used for this sort() function .
const sortRandom = (arr) => arr.sort(() => Math.random() - 0.5)4、 String uppercase
And Python、C# and PHP And other popular programming languages ,JavaScript There is no function that allows string capitalization . however , This is a very basic function , Often used . We can enter a word or a complete sentence in this function , As long as it is a string .
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1)5、 Check whether the variable is an array
There are several ways to check whether a variable is an array , But this is my preferred method —— Clean and easy to understand .
const isArray = (arr) => Array.isArray(arr)6、 from URL Extract hostname from
Although this is not a single line technically , But it is still a very useful function . This is useful for checking whether the link is external or internal . Based on this , We can add different behaviors or styles to some links .
This function is also applicable to URL.
const extractHostname = (url) => {
let hostname = (url.indexOf("//") > -1) ? url.split('/')[2] : url.split('/')[0]
// Remove port number.
hostname = hostname.split(':')[0]
// Remove querystring.
hostname = hostname.split('?')[0]
return hostname
}7、 Get the unique value in the array
A very simple but ingenious skill , You can delete all duplicate values from the array . This technique converts the array we use as the first parameter to Set, Then convert back to the array .
const uniqueValues = (arr) => [...new Set(arr)]8、 Check whether all items in the array meet a certain condition
every Method to check whether all items in the array meet a condition , This method takes the callback as its only parameter and returns a Boolean value .
Tips : If only one element in an array is needed to meet a certain condition , have access to some() Method .
const isOldEnough = (age) => age >= 18
const ages = [7, 19, 12, 33, 15, 49]
ages.every(isOldEnough) // Results in false
const olderPeople = [39, 51, 33, 65, 49]
olderPeople.every(isOldEnough) // Results in true9、 Format floating point numbers according to the locale
Formatting floating-point numbers can be done in many ways . however , If you are developing applications that support multiple locales , The format may be different , The following single line code supports formatted floating-point numbers in different locales .
Tips : If we need to support multiple locales , We can add a third parameter to the locale .
const formatFloat = (floatValue, decimals) => parseFloat(floatValue.toFixed(decimals)).toLocaleString("en-US")10、 Update query string
for example , When using filters , Updating the query string can be very useful , It's a question of how to use it JavaScript Of URLSearchParams Interface update query string example .
const searchParams = new URLSearchParams(window.location.search)
searchParams.set('key', 'value')
history.replaceState(null, null, '?' + searchParams.toString())Please note that , Pass to URLSearchParams Of window.location.search The current query string will remain unchanged . It means , In this case ,key=value Will be added to the current query string . If you want to build the query string from scratch , Please ignore window.location.search Parameters .
11、 Only positive numbers are allowed
Sometimes , We want variables to contain only positive numbers . No need to use if Statement to check whether the number is negative , You can use the following single line :
const getPositiveNumber = (number) => Math.max(number, 0)You can use this single line of code instead of the code snippet shown below :

Math.max() The solution is cleaner , Right ?
12、 Show print dialog
The following line of code displays the print dialog , If you want to provide users with a user-friendly way to print a page on the website , It will help .
const showPrintDialog = () => window.print()13、 Copy text to clipboard
Copying text to the clipboard is a problem that can be solved in many ways .
If you only care about supporting modern browsers , The following example is sufficient :
const copyTextToClipboard = async (text) => {
await navigator.clipboard.writeText(text)
}This is a very clean solution , Do not rely on any DOM Elements .
Please note that , This function is asynchronous , because writeText The function returns a Promise.
however , If you want to support Internet Explorer Wait for the old browser , The following methods must be adopted : This solution relies on input fields , Not based on Promise Solutions for .
// HTML
<input id="input" type="text" value="This is the text that gets copied">
<button id="copy">Copy the text</button>
// JavaScript
const copy = () => {
const copyText = document.querySelector('#input')
copyText.select()
document.execCommand('copy')
}
document.querySelector('#copy').addEventListener('click', copy)14、 Convert all values to an array
We can use on arrays map Function converts all its items to a certain type . In the example , You will see that we first convert a string array to a number array . after , We convert an array of numbers to Boolean values .
const arrayToNumbers = (arr) => arr.map(Number)
const numbers = arrayToNumbers(['0', '1', '2', '3'])
const arrayToBooleans = (arr) => arr.map(Boolean)
const booleans = arrayToBooleans(numbers)15、 Count the number of days between two dates
Count the number of days between two dates , This is one of the things we often encounter in development , If you use it often JavaScript Programming , Use Math.abs(), The order of the date parameters is irrelevant .
const daysBetweenDates = (dateA, dateB) => {
const timeDifference = Math.abs(dateA.getTime() - dateB.getTime())
// Seconds * hours * miliseconds
return Math.floor(timeDifference / (3600 * 24 * 1000))
}
daysBetweenDates(new Date('2020/10/21'), new Date('2020/10/29'))
// Result: 8
daysBetweenDates(new Date('2020/10/21'), new Date('2021/10/29'))
// Result: 37316、 Sort an array of objects
When presenting data in a specific order , It may be useful to know how to sort an array of objects according to specific attributes , Suppose we want to present the results on the page in alphabetical order .
This can be done in JavaScript It is easy to complete , Although we can write code to sort arrays in many ways .
In all the examples , We all used it JavaScript Sorting method of . The first example uses the arrow function .
const people = [
{ firstName: 'Laura', lastName: 'Smith' },
{ firstName: 'John', lastName: 'Wilson' },
{ firstName: 'Ted', lastName: 'Jonhson' }
]
people.sort((firstEl, secondEl) => {
const property = 'lastName'
if (firstEl[property] < secondEl[property]) {
return -1
} else if (firstEl[property] > secondEl[property]) {
return 1
}
return 0
})
// [{firstName: 'Ted', lastName: 'Jonhson'},
// {firstName: 'Laura', lastName: 'Smith'},
// {firstName: 'John', lastName: 'Wilson'}]If you will , You can also refactor it , You may have to use the comparison function in multiple places . under these circumstances , I suggest you use the following implementation , So that you can reuse compareNames function .
const people = [
{ firstName: 'Laura', lastName: 'Smith' },
{ firstName: 'John', lastName: 'Wilson' },
{ firstName: 'Ted', lastName: 'Jonhson' }
]
const compareNames = (firstEl, secondEl) => {
const property = 'lastName'
if (firstEl[property] < secondEl[property]) {
return -1
} else if (firstEl[property] > secondEl[property]) {
return 1
}
return 0
}
people.sort(compareNames)
// [{firstName: 'Ted', lastName: 'Jonhson'},
// {firstName: 'Laura', lastName: 'Smith'},
// {firstName: 'John', lastName: 'Wilson'}]Of course , As the title has revealed , You can even do this on one line . Although if you have a comparison function with a lot of logic , This can quickly become chaotic . If the comparison function is quite simple , I will only choose this implementation .
const people = [
{ firstName: 'Laura', lastName: 'Smith' },
{ firstName: 'John', lastName: 'Wilson' },
{ firstName: 'Ted', lastName: 'Jonhson' }
]
people.sort((firstEl, secondEl) => (firstEl['lastName'] < secondEl['lastName']) ? -1 : (firstEl['lastName'] > secondEl['lastName']) ? 1 : 0)
// [{firstName: 'Ted', lastName: 'Jonhson'},
// {firstName: 'Laura', lastName: 'Smith'},
// {firstName: 'John', lastName: 'Wilson'}]17、 Gets the intersection of arrays
Getting the intersection of arrays may be one of the development problems we often encounter , This may give you a headache . But there is no need to , Because all this can be done with this single line —— This can be a real headache protector .
const intersection = (a, ...arr) => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v)))
intersection([1, 2, 3], [2, 3, 4, 7, 8])
// [2, 3]
intersection([1, 2, 3], [2, 3, 4, 7, 8], [1, 3, 9])
// [3]Please note that , This function can obtain the intersection of more than two arrays at a time .
18、 Get the number of days in a month
In the absence of any external library help JavaScript Dealing with dates can sometimes be painful . But did you know that a clean and simple one-way line can help you get the number of days in a month ?
const daysInMonth = (month, year) => new Date(year, month, 0).getDate()
daysInMonth(2, 2024)
// 29
daysInMonth(12, 2022)
// 3119、 Exchange values in a good way
Exchanging the values of two variables is something you may have done many times before , The old-fashioned way to do this is to use a temporary third variable , As shown below :
let personA = "Laura"
let personB = "John"
let temp = personA
personA = personB
personB = temp
console.log(personA)
// "John"
console.log(personB)
// "Laura"however , We know that JavaScript Is there a simpler solution to exchange the values of two variables in ? Look at the following code line , The actual exchange only occurs on one line .
let personA = "Laura"
let personB = "John"
[personA, personB] = [personB, personA]
console.log(personA)
// 'John'
console.log(personB)
// 'Laura'This solution looks cleaner , isn't it? ?
20、 Flatten array
Use this simple single line , The days when flattening arrays may be a real challenge are over .
const flatten = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flatten(b)] : [...a, b]), [])
flatten([[1, 2], [3, 4], [5, 6]])
// [1, 2, 3, 4, 5, 6]
flatten([["some", "text"], "and", ["some", "more"]])
// ['some', 'text', 'and', 'some', 'more']But there is a shorter way to achieve this . We can call on the array flat Method and get the same result . however , This function is not fully supported . Especially in several older browsers , Lack of support for this feature .
[[1, 2], [3, 4], [5, 6]].flat()
// [1, 2, 3, 4, 5, 6]
[["some", "text"], "and", ["some", "more"]].flat()
// ['some', 'text', 'and', 'some', 'more']21、 Replace multiple spaces with one space
Dealing with spaces can be annoying , One of the most common problems with spaces is that you have to deal with multiple spaces . Fortunately, , We can replace them with a single space .
const replaceSpaces = (str) => str.replace(/\s\s+/g, ' ')
replaceSpaces('Too many spaces')
// 'Too many spaces'Sometimes , We may also want to replace other white space characters , For example, tabs and line breaks . We can also replace them with a space in a line .
const replaceSpaces = (str) => str.replace(/\s\s+/g, ' ')
replaceSpaces('too\n many \twhitespaces \rin here')
// 'too many whitespaces in here'22、 Sort the elements of the array in random order
Sometimes , I want to shuffle the elements of the array . for example , When shuffling . There is no standard JavaScript Function can perform this operation for . But it can be done with very short but powerful lines of code .
Please note that , The items of the array need not be of the same type .
const sortRandom = (arr) => arr.sort(() => Math.random() - 0.5)
sortRandom([1, 2, 3, 4, 5])
// [4, 3, 2, 5, 1]
sortRandom(["Some text", 2, true, 4, 94.12])
// ['Some text', 94.12, 2, true, 4]23、 Check whether the two objects are equal
Compare objects and check whether they are equal , in the majority of cases , Comparing objects is better than just objectA === objectB It's a little bit more complicated . however , It can be done in one line of code .
The beauty of this function is that it can also check more than two objects .
const isEqual = (...objects) => objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0]))
isEqual({ name: 'Frank', age: 32 }, { name: 'Frank', age: 32 })
// true
isEqual({ name: 'Frank', age: 41 }, { name: 'Frank', age: 32 })
// false
isEqual({ name: 'Frank', age: 32 }, { name: 'Frank', age: 32 }, { name: 'Frank', age: 32 })
// true
isEqual({ name: 'Frank', age: 32 }, { name: 'Frank', age: 32 }, { name: 'Lisa', age: 32 })
// false24、 Get random items from the array
Getting random items from an array is another powerful single line code that can sometimes be used . Whether you try to get a random value from an array full of numbers or not , Objects are a combination of the two .
const getRandomItem = arr => arr[Math.floor(Math.random() * arr.length)]
getRandomItem([1, 7, 9, 3, 6])
// 6
getRandomItem([{ name: "Ted" }, { name: "Philip" }, { name: "Jack" }])
// { name: "Philip" }
getRandomItem([{ name: "Ted" }, 1, "Some text", 4, { name: "Jack" }])
// 'Some text'25、Slugify A string
If you want to generate human readable URL, You can use slugify .slug Is a normalized version of the representative string . Most of the time , The title is used for slug.
https://mywebsite.com/my-first-blog-postThis is it. slug The appearance of .my-first-blog-post From blog title “ My first blog post ”.
const slugify = (str) => str.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, '')
slugify('The first post: What is going on?') // 'the-first-post-what-is-going-on'You may see this all the time URL, Because it is created human readable URL The most commonly used method of . But you know in JavaScript You only need one line of code in to perform slugify Do you deal with it ?
At the end
The above is our summary 25 about JavaScript Single line code list . I hope you have learned oneortwo new knowledge , If you also know more single line coding techniques , Please remember to share with us in the message area .
If you think my content today is useful to you , Please remember to praise me , Pay attention to me , And share it with your development friends , Maybe it can help them .
Last , Thanks for reading , Happy programming , I'll see you next time .
Learn more skills
Please click below official account.
![]()
边栏推荐
- 随机梯度下降法、牛顿法、冲量法、AdaGrad、RMSprop以及Adam优化过程和理解
- 919. 完全二叉树插入器
- Rainbond插件扩展:基于Mysql-Exporter监控Mysql
- Bash does not add single quotes to your string
- Is there a "fingerprint" in the structure of AAAI 2022 | Gan? Generating network structure from forged image traceability
- 919. Complete binary tree inserter
- Internal network planning and design of Yingcheng hospital
- 安全基础6 ---漏洞复现
- 高端旗舰投影仪选购指南:当贝X3 Pro、当贝F5观影更沉浸!
- tiktok如何破零播放?
猜你喜欢

高端旗舰投影仪选购指南:当贝X3 Pro、当贝F5观影更沉浸!

JS learning notes 17: DOM query exercise
![Interpretation of repartitioned network structure in repvgg network [with code]](/img/0b/a2f3b312899043c9d5b9c7d6b22261.png)
Interpretation of repartitioned network structure in repvgg network [with code]

03 isomorphism of tree 1

授权无线通信标准

Binary tree visualization

How to be a self disciplined person?

Illegal mix of collations for operation ‘UNION‘(bug记录)

微信小程序开发之网络数据请求

Mobile phone touch picture slider rotation plug-in photoswipe.js
随机推荐
How to be a self disciplined person?
High number_ Chapter 3 learning experience and summary of multiple integral
Rainbond插件扩展:基于Mysql-Exporter监控Mysql
六轴传感器使用学习记录
重磅!《几何深度学习》新书发布,帝国理工/DeepMind等图ML大牛共同撰写,160页pdf阐述几何DL基础原理和统一框架
手机端触摸图片slider轮播插件photoswipe.js
[server data recovery] a data recovery case of a brand ProLiant server raid paralysis, database file loss, and database file backup damage
UNET and mask RCNN
Detailed explanation of three methods of selenium setting element waiting
University of California | feasible confrontation robust reinforcement learning for unspecified environments
919. 完全二叉树插入器
what is qml in qt
Illegal mix of collations for operation ‘UNION‘(bug记录)
Amrita Institute of Engineering | reinforcement active learning method for optimizing sampling in terms extraction of emotional analysis
NPM semantic version control, solution console prop being mutated: "placement" error
Istio exposes applications to the Internet
Internal network planning and design of Yingcheng hospital
Add a subtitle of 3D effect to the container
[wp]ctfshow-web入门信息搜集
Selenium 设置元素等待的三种方式详解