A summary of the methods of generating random numbers by JS [Favorites]

Source: Internet
Author: User

A summary of the methods of generating random numbers by JS

JS generates random numbers primarily using the random () method of the built-in math object. Usage such as: Math.random (). It returns a random number between 0 and 1. With such a method, it is understandable to generate arbitrary random numbers. For example, in practice we may have the following needs:

(1) generate a random integer between 0-100, then you can:

    1. parseint (100*math.random ());

Note: Because the return value of Math.random () is 0 and 1, there is the possibility of generating 0 and 100.

(2) generate a random integer from M-n, for example to generate a random number between 5-15, you can:

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

The summary is:

parseint (Math.random () * (n-m+1) +m);//Generate a random integer from M-n

In addition, according to the need www.phpernote.com summed up the other two commonly used methods, as follows:

(1) generating a random integer of the specified number of digits

    1. function Randomnum (n) {
    2. var t=';
    3. For (var i=0;i<n;i++) {
    4. T+=math.floor (Math.random () *10);
    5. }
    6. return t;
    7. }

(2) Generate random integers in the specified range

  1. function Randomnum (minnum,maxnum) {
  2. switch (arguments.length) {
  3. Case 1:
  4. return parseint (Math.random () *minnum+1);
  5. Break ;
  6. Case 2:
  7. return parseint (Math.random () * (maxnum-minnum+1) +minnum);
  8. Break ;
  9. Default:
  10. return 0;
  11. Break ;
  12. }
  13. }

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

This article original address: http://www.daimajiayuan.com/sitejs-17200-1.html

A summary of the methods of generating random numbers by JS [Favorites]

Related Article

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.