In JavaScript, you can use the Math.random() function to generate random numbers from 0 to 1, or you can set the value of the function to generate random numbers in any range or different ones. Random number
In JavaScript, you can use the Math.random() function to generate a random number between 0 and 1, but this often cannot meet our daily needs. But we can use other methods to make it generate the random numbers we want. What I will share with you today is to generate random numbers through the Math.random() function, which has a certain reference effect and I hope it will be helpful to everyone.

【Recommended courses: JavaScript Tutorial, JavaScript Tutorial Manual】
Random number generation
In JavaScript, random numbers from 0 to 1 can be generated through the following statement:
Math.round(Math.random());
If we want to set it in a specified range The random numbers in can also be generated by the above function
Example: Generate random numbers between 8 and 100
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> var num=Math.floor(Math.random()*100+8); document.write(num); </script> </head> <body> </body> </html>
Rendering:

If you want to generate a range from 10 to 100, you only need to change the following number 8 to 10. We can use the above method Implement the generation of random numbers within a custom range
Generate non-repeating random numbers
Sometimes random numbers can be generated through specific methods but there will be no differences between them Repeat, as shown below
<script>
// 定义存放生成随机数的数组
var array=new Array();
// 循环N次生成随机数
for(var i = 0 ; ; i++){
// 只生成10个随机数
if(array.length<10){
generateRandom(10);
}else{
break;
}
}
// 循环遍历随机数数组
for(var i = 0 ; i < array.length; i++){
document.write(array[i]);
}
// 生成随机数的方法
function generateRandom(count){
var rand = parseInt(Math.random()*count);
for(var i = 0 ; i < array.length; i++){
if(array[i] == rand){
return false;
}
}
array.push(rand);
}
</script>Rendering:

The above is the detailed content of How to generate random numbers in javascript. For more information, please follow other related articles on the PHP Chinese website!