Home > Web Front-end > JS Tutorial > How to use random() function

How to use random() function

不言
Release: 2019-02-14 10:47:00
Original
53617 people have browsed it

The random() function can be used to return a floating-point pseudo-random number in the range 0 (inclusive) to 1 (exclusive). This random number can then be scaled according to the required range. Let's take a look at the specific use of the random() function.

How to use random() function

Let’s first take a look at the basic syntax of the random() function

Math.random()
Copy after login

math.random() function return range is [ 0,1).

Let’s look at a specific example

Get a random number between [0,1)

The code is as follows

<!DOCTYPE html>
<html>
<head>
   <title></title>
</head>
<body>
<script type="text/javascript"> 
    var random = Math.random( ); 
    document.write("生成的随机数 : " + random );  
</script> 
</body>
</html>
Copy after login

The running result is:

生成的随机数 : 0.8336114321997108
Copy after login

Get a random number between two values: Math.random() can be used to get a random number between two values. The return value is [min,max).

The code is as follows

<!DOCTYPE html>
<html>
<head>
   <title></title>
</head>
<body>
<script type="text/javascript"> 
    var min=4; 
    var max=5;  
    var random = Math.random() * (+max - +min) + +min; 
    document.write("生成的随机数 : " + random );  
</script> 
</body>
</html>
Copy after login

The running result is:

生成的随机数 : 4.887121143160121
Copy after login

Get a random integer between two values: Math.random() Can be used to get an integer between two values. If min is not an integer, the return value is not less than min or the next integer greater than min, and is less than but not equal to max.

The code is as follows

<!DOCTYPE html>
<html>
<head>
   <title></title>
</head>
<body>
<script type="text/javascript"> 
    var min=4; 
    var max=8;  
    var random =Math.floor(Math.random() * (+max - +min)) + +min; 
    document.write("生成的随机数 : " + random );  
</script> 
</body>
</html>
Copy after login

The running result is:

生成的随机数 : 6
Copy after login

This article ends here. For more exciting content, you can pay attention to other related columns of the php Chinese website Tutorial! ! !

The above is the detailed content of How to use random() function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template