


33 very practical JavaScript one-line codes, it is recommended to collect them!
This article brings you 33 very practical JavaScript one-line codes, organized and shared with you. These methods use some APIs to simplify the operation, but some methods are not very elegant to write one line, so here are the main ones Learn how to use API! I hope everyone has to help.
1. Date processing
1. Check whether the date is valid
This method is used to check whether the given date is valid:
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf()); isDateValid("December 17, 1995 03:24:00"); // true
2. Calculate the interval between two dates
This method is used Calculate the time interval between two dates:
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000) dayDif(new Date("2021-11-3"), new Date("2022-2-1")) // 90
3. Find the day of the year on which the date is located
This method is used to detect the given date The day of the year:
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); dayOfYear(new Date()); // 307
2021 has passed
4. Time formatting
This method can be used to convert time The format of hour:minutes:seconds:
const timeFromDate = date => date.toTimeString().slice(0, 8); timeFromDate(new Date(2021, 11, 2, 12, 30, 0)); // 12:30:00 timeFromDate(new Date()); // 返回当前时间 09:00:00
2. String processing
1. Capitalize the first letter of the string
This method is used to capitalize the first letter of an English string:
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1) capitalize("hello world") // Hello world
2. Flip the string
This method is used to Flip a string and return the flipped string:
const reverse = str => str.split('').reverse().join(''); reverse('hello world'); // 'dlrow olleh'
3. Random string
This method is used to generate a random string:
const randomString = () => Math.random().toString(36).slice(2); randomString();
4. Truncate the string
This method can truncate the string from the specified length:
const truncateString = (string, length) => string.length < length ? string : `${string.slice(0, length - 3)}...`; truncateString('Hi, I should be truncated because I am too loooong!', 36) // 'Hi, I should be truncated because...'
5. Remove the string HTML in
This method is used to remove HTML elements from a string:
const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
3. Array processing
1. Remove duplicate items from the array
This method is used to remove duplicate items from the array:
const removeDuplicates = (arr) => [...new Set(arr)]; console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));
2. Judge the array Whether it is empty
This method is used to determine whether an array is an empty array. It will return a Boolean value:
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0; isNotEmpty([1, 2, 3]); // true
3. Merge two arrays
You can use the following two methods to merge two arrays:
const merge = (a, b) => a.concat(b); const merge = (a, b) => [...a, ...b];
4. Number operations
1. Determine whether a number is odd or even
This method is used to determine whether a number is odd or even:
const isEven = num => num % 2 === 0; isEven(996);
2. Obtain the average of a set of numbers
const average = (...args) => args.reduce((a, b) => a + b) / args.length; average(1, 2, 3, 4, 5); // 3
3. Get a random integer between two integers
This method is used to get a random integer between two integers
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min); random(1, 50);
4. Rounding to specified digits
This method is used to round a number to specified digits:
const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d) round(1.005, 2) //1.01 round(1.555, 2) //1.56
5. Color operation
1. Convert RGB to hexadecimal mechanism
This method can convert an RGB color value into a hexadecimal value:
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); rgbToHex(255, 255, 255); // '#ffffff'
2. Get a random hexadecimal color
This method is used to get a random hexadecimal color value:
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`; randomHex();
6. Browser operation
1. Copy the content to the clipboard
This method uses navigator.clipboard.writeText To copy text to the clipboard:
const copyToClipboard = (text) => navigator.clipboard.writeText(text); copyToClipboard("Hello World");
2. Clear all cookies
This method can access cookies and clear them stored in the web page by using document.cookie All cookies:
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
3. Get the selected text
This method gets the text selected by the user through the built-in getSelection property:
const getSelectedText = () => window.getSelection().toString(); getSelectedText();
4. Detect whether it is dark mode
This method is used to detect whether the current environment is dark mode, it is a Boolean value:
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches console.log(isDarkMode)
5. Scroll Go to the top of the page
This method is used to return to the top of the page:
const goToTop = () => window.scrollTo(0, 0); goToTop();
6. Determine whether the current tab is activated
The This method is used to detect whether the current tab page has been activated:
const isTabInView = () => !document.hidden;
7. Determine whether the current device is an Apple device
This method is used to detect whether the current device is an Apple device Device:
const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform); isAppleDevice();
8. Whether to scroll to the bottom of the page
This method is used to determine whether the page has reached the bottom:
const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
9. Redirect to a URL
This method is used to redirect to a new URL:
const redirect = url => location.href = url redirect("https://www.google.com/")
10. Open the browser print box
This method is used to open the print box of the browser:
const showPrintDialog = () => window.print()
7. Other operations
1. Random Boolean value
This method can return a random Boolean value. Use Math.random() to get a random number from 0-1. Compared with 0.5, there is a half probability of getting a true or false value. .
const randomBoolean = () => Math.random() >= 0.5; randomBoolean();
2. Variable exchange
You can use the following form to exchange the values of two variables when the third variable is not applicable:
[foo, bar] = [bar, foo];
3. Get the type of variable
This method is used to get the type of a variable:
const trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase(); trueTypeOf(''); // string trueTypeOf(0); // number trueTypeOf(); // undefined trueTypeOf(null); // null trueTypeOf({}); // object trueTypeOf([]); // array trueTypeOf(0); // number trueTypeOf(() => {}); // function
4. Conversion between Fahrenheit and Celsius
该方法用于摄氏度和华氏度之间的转化:
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32; const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9; celsiusToFahrenheit(15); // 59 celsiusToFahrenheit(0); // 32 celsiusToFahrenheit(-20); // -4 fahrenheitToCelsius(59); // 15 fahrenheitToCelsius(32); // 0
5. 检测对象是否为空
该方法用于检测一个JavaScript对象是否为空:
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
【相关推荐:javascript学习教程】
The above is the detailed content of 33 very practical JavaScript one-line codes, it is recommended to collect them!. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

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



Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.
