Playing with code | those practical JavaScript single-line codes to help you work easily

Table of contents

Array deduplication

Get parameters from url and convert to object

Check if object is empty

reverse string

generate random hex

Check if the current tab is in the background

Check if element is in focus

 Check device type

Copy text to clipboard

get selected text

Query whether a day is a working day

Convert Fahrenheit/Celsius

The difference in days between two dates

Convert RGB to hex

Calculates the average of an array


This article organizes very useful single-line codes. These requirements are very common in development. Using single-line codes can help you improve your work efficiency. Complete the project faster and more efficiently. Although it is a short line of code, its value in the project is unlimited, so hurry up and collect it.

Array deduplication

There are many ways to delete all duplicate values ​​from an array. Here we will talk about the simplest way, which can be done with one line of code:

Set is a series of data collections that are unordered and have no duplicate values. Pass in an array that needs to be deduplicated, and Set will automatically delete duplicate elements

Then convert the Set to an array and return it. This method is efficient and the code is clear. The disadvantage is that there are compatibility issues.

const uniqueArr = (arr) => [...new Set(arr)];

console.log(uniqueArr(["前端","js","html","js","css","html"]));
// ['前端', 'js', 'html', 'css']

uniqueArrThe method converts the data into a Set, and then destructures it into an array and returns it.

 

Get parameters from url and convert to object

The path of the web page is often: www.baidu.com?search=js&xxx=kkkin this form, we often need to get parameters, which can be realized by using a third-party qspackage. If you just want to achieve parameter removal, this line of code can be realized, and there is no need to introduce it qs.

const getParameters = URL => JSON.parse(`{"${decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`
  )

getParameters("https://www.google.com.hk/search?q=js+md&newwindow=1");
// {q: 'js+md', newwindow: '1'}

 

Check if object is empty

Checking whether the object is empty is actually not that simple, even if the object is empty, every time checking whether the object is equal  {} will return  false.

Fortunately, the following one-liners help us solve it perfectly.

1、

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
isEmpty({}) // true
isEmpty({a:"not empty"}) //false

2. Convert the object into a string, and then judge whether it is equal to "{}"

let obj = {};
console.log(JSON.stringify(obj) === "{}");//返回true


3. The Object.keys() method returns an array of object property names. If the length is 0, an empty object is returned (ES6 writing method)

console.log(Object.keys(obj).length == 0);//返回true

4. The Object.getOwnPropertyNames() method obtains the property name of the object and stores it in an array. If the length is 0, it is an empty object

console.log(Object.getOwnPropertyNames(obj).length == 0);//返回true


5. The isEmptyObject() method in jQuery, its principle is to use the for in method to judge (note: remember to quote jQuery when using this method)

console.log($.isEmptyObject(obj));//返回true

 

reverse string

Reversing a string can be easily achieved using splitthe combine reverseand joinmethod.

const reverse = str => str.split('').reverse().join('');
reverse('this is reverse');
// esrever si siht

 

 

generate random hex

I believe you can generate random numbers at your fingertips, then randomly generate hexadecimal numbers, such as generating hexadecimal color values.

const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`
console.log(randomHexColor());
// #a2ce5b

  

Check if the current tab is in the background

The browser uses tabbed browsing, and any webpage may be in the background. At this time, the user is not browsing. Do you know how to quickly detect whether your webpage is hidden or visible to the user?

const isTabActive = () => !document.hidden; 

isTabActive()
// true|false

  

Check if element is in focus

activeElement Property returns the currently focused element in the document.

onst elementIsInFocus = (el) => (el === document.activeElement);

elementIsInFocus(anyElement)
// 元素处于焦点返回true,反之返回false

 Using jQuery, you can easily add event listeners. Here is a simple example:

$('input').on('focus', function() {    console.log('input is focused!');});

In the above example, we added focus event listeners to all input elements. When one of the elements is focused, "input is focused!" will be output on the console.

So, how to detect whether an element is focused? You can use the :focus pseudo-class selector provided by jQuery, which can select the currently focused element. For example:

if ($('#myInput:focus').length > 0) {

    console.log('myInput is focused!');

}

In the above code, we use jQuery's selector syntax to select the input box with id myInput and determine whether it is focused. If the input box is focused, output "myInput is focused!".

 Check device type

Use to navigator.userAgent determine whether it is a mobile device or a computer device:

const judgeDeviceType =
      () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'PC';

judgeDeviceType()  // PC | Mobile

 

Copy text to clipboard

Clipboard API All its operations are asynchronous, returning  Promise objects without causing page freezes. Moreover, it can put arbitrary content (such as pictures) into the clipboard.

const copyText = async (text) => await navigator.clipboard.writeText(text)
copyText('单行代码 前端世界')

get selected text

getSelection Get the text selected by the user using the built-in  :

const getSelectedText = () => window.getSelection().toString();

getSelectedText();
// 返回选中的内容

 

Query whether a day is a working day

When we write our own calendar components, we often use it to judge whether a certain date is a working day; Monday to Friday are working days:

const isWeekday = (date) => date.getDay() % 6 !== 0;

isWeekday(new Date(2022, 03, 11))
// true

  

Convert Fahrenheit/Celsius

Dealing with temperatures can be confusing at times. These two functions help you convert Fahrenheit to Celsius and Celsius to Fahrenheit.

  • Convert Fahrenheit to Celsius
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;

fahrenheitToCelsius(50);
// 10
  • Convert Celsius to Fahrenheit
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;

celsiusToFahrenheit(100)
// 212

 

 

The difference in days between two dates

In daily development, we often encounter the need to display the remaining days. Generally, we need to calculate the number of days between two dates:

const dayDiff = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);

dayDiff(new Date("2021-10-21"), new Date("2022-02-12"))
// Result: 114

Convert RGB to hex

const rgbToHex = (r, g, b) =>   "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(255, 255, 255); 
//  #ffffff

Calculates the average of an array

There are many ways to calculate the average value, and the calculation logic is the same, but the implementation methods are different. One line of code is simple to implement:

const average = (arr) => arr.reduce((a, b) => a + b) / arr.length;
average([1,9,18,36]) //16

 

 

Guess you like

Origin blog.csdn.net/qq_22903531/article/details/131437824