JavaScript generates random integers n to M

Source: Internet
Author: User

Summary:

This article explains how to use JS to generate random numbers between N and M, the main purpose is to prepare for the later JS generation verification code.

The Math.random () function returns a pseudo-random number between 0 and 1, which may be 0, but is always less than 1,[0,1)

Generates an integer that contains n but does not contain m: n-m

The first step is to calculate the value of the m-n, assuming equal to W

Step two math.random () *w

Step three math.random () *w+n

Fourth Step parseint (Math.random () *w+n, 10)

Generate N-M, not containing n but an integer with M:?

The first step is to calculate the value of the m-n, assuming equal to W

Step two math.random () *w

Step three math.random () *w+n

Fourth Step Math.floor (Math.random () *w+n) + 1

Generate N-m, with no integers of N and M:

The first step is to calculate the value of the m-n-2, assuming equal to W

Step two math.random () *w

Step three math.random () *w+n +1

Fourth Step Math.Round (Math.random () *w+n+1) or Math.ceil (Math.random () *w+n+1)

Generate N-M, containing random numbers of N and M:

The first step is to calculate the value of the m-n, assuming equal to W

Step two math.random () *w

Step three math.random () *w+n

Fourth Step Math.Round (Math.random () *w+n) or Math.ceil (Math.random () *w+n)

Example:

Generates a random integer of 800-1500 that contains 800 but does not contain 1500

    1. 1500-800 = 700
    2. Math.random () *700
    3. var num = math.random () *700 + 800;
    4. num = parseint (num, 10);

It takes just four simple steps to complete.

Add:

Math.ceil () returns the smallest integer greater than or equal to the number parameter (rounding function) to round the number

Math.floor () returns the largest integer less than or equal to the number parameter, rounding the number down

Math.Round () returns the nearest integer of the number, rounded

JavaScript generates random integers n to M

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.