Home>Article>Web Front-end> How to generate random numbers in javascript

How to generate random numbers in javascript

清浅
清浅 Original
2019-02-15 11:04:10 24799browse

In JavaScript, you can use the Math.random() function to generate random numbers from 0 to 1, or you can set the value of the function to generate random numbers in any range or different ones. Random number

In JavaScript, you can use the Math.random() function to generate a random number between 0 and 1, but this often cannot meet our daily needs. But we can use other methods to make it generate the random numbers we want. What I will share with you today is to generate random numbers through the Math.random() function, which has a certain reference effect and I hope it will be helpful to everyone.

How to generate random numbers in javascript

【Recommended courses:JavaScript Tutorial,JavaScript Tutorial Manual

Random number generation

In JavaScript, random numbers from 0 to 1 can be generated through the following statement:

Math.round(Math.random());

If we want to set it in a specified range The random numbers in can also be generated by the above function

Example: Generate random numbers between 8 and 100

    Document 

Rendering:

How to generate random numbers in javascript

If you want to generate a range from 10 to 100, you only need to change the following number 8 to 10. We can use the above method Implement the generation of random numbers within a custom range

Generate non-repeating random numbers

Sometimes random numbers can be generated through specific methods but there will be no differences between them Repeat, as shown below

Rendering:

How to generate random numbers in javascript

##We can see from the above picture that each generated All random numbers are different

Summary: The above is the entire content of this article. I hope this article can help everyone learn how to generate random numbers.

The above is the detailed content of How to generate random numbers in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:How to use forEach method Next article:How to use forEach method