Home > Article > Web Front-end > How to use random() function
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.
Let’s first take a look at the basic syntax of the random() function
Math.random()
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>
The running result is:
生成的随机数 : 0.8336114321997108
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>
The running result is:
生成的随机数 : 4.887121143160121
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>
The running result is:
生成的随机数 : 6
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!