Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the JavaScript single-line programs?

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

What are the JavaScript single-line programs? in view of this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

There are more than 10 million Javascript developers worldwide, and that number is growing every day. Although JavaScript is better known for its dynamic features, it also has many other great features.

1. Random ID generation

This can be your preferred feature when you are prototyping and need a unique id.

Const a = Math.random (). ToString (36) .substring (2); console.log (a)-- 72pklaoe38u2. Random numbers within the generated range

In many cases, we need to generate a random number in a range. The Math.random function can help us generate random numbers and then convert them to the desired range.

Max = 20 min = 10 var a = Math.floor (Math.random () * (max-min + 1)) + min; console.log (a)-173. Random array (shuffle)

In JavaScript, we don't have a module because python has random.shuffle (), but there is still a way to shuffle an array in one line of code.

Var arr = ["A", "B", "C", "D", "E"]; console.log (arr.slice (). Sort (() = > Math.random ()-0.5))-- ['C','B','A','D','E'] 4. Get random Boolean value

The Math.random function in Javascript can be used to generate random numbers between ranges. To generate a random Boolean, we need to randomly take a number between 0 and 1, and then check to see if it is greater than or less than 0.5.

Const randomBoolean = () = > Math.random () > = 0.5; console.log (randomBoolean ());-- false5. Generate random hexadecimal code

You can use this one-liner to challenge your abilities as a web developer. This one-liner will generate a random hexadecimal code. You can use an one-line program to generate 3-6 color codes, which will create a color tray for you.

Console.log ('#'+ Math.floor (Math.random () * 0xffffff) .toString (16) .padEnd (6,'0')) -1st Run- # 48facd-2nd Run- # 93d806-3rd Run- # 9072f96. Reverse string

There are many ways to reverse strings, but this is one of the easiest ways I've found on the Internet.

Const reverse = str = > str.split (''). Reverse (). Join (''); console.log (reverse ('javascript'));-- tpircsavaj7. Swap two variables

The following code shows some simple ways to exchange two variables without using a third variable, just one line of code.

A = 5b = 7-method 1-b = [a, a = b] [0]; / One Liner-method 2-[arecedence b] = [bjurisdiction a]; console.log ("A =", a) console.log ("B =", b) 8. Multivariable distribution

Like Python, JavaScript can also use this clever deconstruction technique to assign multiple variables to the same line of code at the same time.

Var [a forerunner brecory c COD d] = [20pr 14je 30, "COD"] console.log (a recorder breco c r r d)-- 20 14 30 COD

9. Check for even and odd numbers

There are many ways to do this, and one of the easiest ways to do this is to use the arrow function and write the entire code in one line.

Const isEven = num = > num% 2 = = 0; console.log (isEven (2));-- true console.log (isEven (3));-- false10.FizzBuzz

This question is one of the famous interview questions used to examine the core of programmers. In this test, we need to write a program to print numbers from 1 to 100. However, if it is a multiple of 3, print "Fizz" instead of a number, and if it is a multiple of 5, print "Buzz".

For (join) = = str.split (''). Reverse (). Join (''); result = isPalindrome ('abcba'); console.log (result)-true result = isPalindrome (' abcbc'); console.log (result)-false12. Check whether all elements in the array meet specific conditions const hasEnoughSalary = (salary) = > salary > = 30000 const salarys = [70000, 19000, 12000, 30000, 15000, 50000] result = salarys.every (hasEnoughSalary) console.log (result)-- false const salarys = [70,000,190,000,120,000,30000 150050000] result = salarys.every (hasEnoughSalary) / / Results in false console.log (result)-- true

13. Calculate the number of days between two given dates

Const days = (date, otherDate) = > Math.ceil (Math.abs (date-otherDate) / (86400000)); result = days (new Date ('2020-04-15'), new Date ('2021-01-15'); console.log (result)-275

To calculate the number of days between two dates, we first find the absolute value between two dates, then divide it by 86400000, which is equal to the number of milliseconds in a day, and finally, we round up and return the result.

14. Convert a string to a number

A very simple way to convert a string to a number is to use type conversion.

ToNumber = str = > + str; toNumber = str = > Number (str); result = toNumber ("2"); console.log (result) console.log (typeof (result))-- 2 number15. Merge multiple arrays const cars = ['?','?]; const trucks = ['?','?];-method 1-const combined = cars.concat (trucks) Console.log (combined)-- ['?','?]-method 2-const combined = [] .concat (cars,trucks) Console.log (combined)-['?','?] 16. Truncate a number to a fixed decimal point

With Math.pow () you can truncate a number to a decimal point.

Const toFixed = (n, fixed) = > ~ (Math.pow (10, fixed) * n) / Math.pow (10, fixed);-toFixed (25.198726354, 1); / / 25.1 toFixed (25.198726354, 2) / 25.19 toFixed (25.198726354, 3); / 25.198 toFixed (25.198726354, 4); / 25.1987 toFixed (25.198726354, 5); / 25.19872 toFixed (25.198726354, 6); / 25.19872617. Scroll to the top of the page

The window.scrollTo () method can help you get the job done. It needs to scroll to the x and y coordinates of that location on the page. If you set them to (0re0), it scrolls to the top of the page.

Const goToTop = () = > window.scrollTo (0,0); goToTop (); 18. Convert Fahrenheit to Celsius (and vice versa)

Whether you choose Fahrenheit or Celsius, it is always a better idea to convert all temperature parameters to one unit.

Const celsiusToFahrenheit = (celsius) = > celsius * 9 fahrenheitToCelsius 5 + 32; const fahrenheitToCelsius = (fahrenheit) = > (fahrenheit-32) * 5max 9;-Examples- celsiusToFahrenheit (15); / / 59 celsiusToFahrenheit (- 20); / /-4 fahrenheitToCelsius (59); / / 15 fahrenheitToCelsius (32); / / 019. The value of a specific Cookie cookie = name = > `; ${[xss_clean]} `.split (`; ${name} = `). Pop (). Split (';'). Shift (); cookie ('_ ga'); / / Result: "GA1.3.974792242.1509957189" 20. Copy text to the clipboard

Copying text to the clipboard is very useful and a difficult problem to solve. You can find a variety of solutions on Internet, but the following solution may be one of the smallest and smartest.

Const copyTextToClipboard = async (text) = > {await navigator.clipboard.writeText (text)} 21. Delete HTML tags

This single-line code uses regular expressions to remove any string that looks like, where x can be any character, including /

"A" .replace (/] + > / gi, ""); 22. Clone array

It returns a copy of the original array.

OldArray = [1, 4, 2, 3] var newArray = oldArray.slice (0) Console.log (newArray)-- [1Magne4Magne2Jol 3] the answers to the questions about the JavaScript one-line program are shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report