JavaScript random()Method

Math 对象参考手册JavaScript Math Object

Example

Return a random number between 0 (inclusive) and 1 (exclusive):

Math.random();

Output:


Try it Yourself »

Definition and Usage

The random() method returns a random number between 0 (inclusive) and 1 (exclusive).


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the random() method


Syntax

Math.random()

Return Value

Type Description
Number A pseudo-random number between 0.0 and 1.0 (exclusive).

Technical Details

JavaScript Version: 1.0


More Examples

Example

In this example, we will get a random number between 1 and 10:

Math.floor((Math.random()*10)+1);

Output:


Try it Yourself »

Example

In this example, we will get a random number between 1 and 100:

Math.floor((Math.random()*100)+1);

Output:


Try it Yourself »

Example

The following function returns a number between min (inclusive) and max (exclusive):

function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min) ) + min; }

Try it Yourself »

Example

The following function returns a number between min (inclusive) and max (inclusive):

function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min + 1) ) + min; }

Try it Yourself »


Math 对象参考手册JavaScript Math Object

Other Extensions