Javascript generates random numbers in a specific range. [four details] _ javascript tips-JS tutorial

Source: Internet
Author: User
The following small series will bring you an article on how to generate a random number in a specific range in JS [four situations ]. I think this is quite good. Now I will share it with you and give you a reference. Let's take a look at the preface:

JS does not have ready-made functions and can directly generate random numbers within a specified range.

However, it has a function: Math. random (), which can generate a random number of [0, 1.

With this, we can generate a random number within the specified range.

If the range is involved, there is a boundary value problem. In this way, there are four situations:

1) min ≤ r ≤ max (this is common)

2) min ≤ r <max

3) min <r ≤ max

4) min <r <max

1. min ≤ r ≤ max

Function RandomNumBoth (Min, Max) {var Range = Max-Min; var Rand = Math. random (); var num = Min + Math. round (Rand * Range); // rounding return num ;}

2. min ≤ r <max

Function RandomNum (Min, Max) {var Range = Max-Min; var Rand = Math. random (); var num = Min + Math. floor (Rand * Range); // return num ;}

3. min <r ≤ max

function RandomNum(Min, Max) {      var Range = Max - Min;      var Rand = Math.random();      if(Math.round(Rand * Range)==0){               return Min + 1;      }      var num = Min + Math.round(Rand * Range);      return num;}

Iv. min <r <max

function RandomNum(Min, Max) {      var Range = Max - Min;      var Rand = Math.random();      if(Math.round(Rand * Range)==0){        return Min + 1;      }else if(Math.round(Rand * Max)==Max)      {        index++;        return Max - 1;      }else{        var num = Min + Math.round(Rand * Range) - 1;        return num;      } }

The above JS generates a random number in a certain range [four situations] is all the content shared by Alibaba Cloud xiaobian. I hope you can give us a reference and support for me.

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.