How to generate a random number using js _ javascript skills

Source: Internet
Author: User
The main content of this article is to summarize the examples of js random number generation methods. js random number generation mainly uses the built-in Math object's random () method, for more information about how to generate a random number using js, you can use the random () method of the built-in Math object. Usage example: Math. random (). It returns a 0 ~ A random number between 1. With this method, it is easy to understand how to generate any random number. For example, we may have the following requirements:
(1) generate a random integer between 0 and 100, then you can:

parseInt(100*Math.random()); 

Note: because the return values of Math. random () include 0 and 1, it is possible to generate 0 and 100.
(2) generate a random integer between m-n. For example, to generate a random number between 5-15, you can:

parseInt(Math.random()*(15-5+1) + 5); 

In general, it is:

ParseInt (Math. random () * (n-m + 1) + m); // generates a random integer between m-n.

In addition, the following two common methods are summarized as needed:
(3) generate a random integer with the specified number of digits

Function randomNum (n) {var t = ''; for (var I = 0; I
 
  

(4) generate a random integer in the specified range

function randomNum(minNum,maxNum){  switch(arguments.length){  case 1:   return parseInt(Math.random()*minNum+1);  break;  case 2:   return parseInt(Math.random()*(maxNum-minNum+1)+minNum);  break;  default:   return 0;  break;  } } 

For example, to generate a random integer between 2-9, then: randomNum (), generate a random integer between 1-22, then: randomNum (22)

The above is the method used to generate random numbers in summary js. I hope it will be helpful for your learning.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.