利用JavaScript生成随机数字!
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>1-99的随机数字</title> 5 <script type="text/javascript"> 6 7 function selectFrom(lowerValue, upperValue) { 8 var choices = upperValue - lowerValue + 1; 9 return Math.floor(Math.random() * choices + lowerValue); 10 } 11 12 var num = selectFrom(1, 99); 13 alert(num); //number between 1 and 99 14 15 </script> 16 </head> 17 <body> 18 19 </body> 20 </html>
本例中使用了Math对象的Math.floor()方法以及random()方法!
那么我要生成1到99范围内9个不重复的数字,而且以数组形式输出呢?
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>不重复的9个属于1-99的随机数字</title> 5 <script type="text/javascript"> 6 7 function selectFrom(lowerValue, upperValue) { 8 var choices = upperValue - lowerValue + 1; 9 return Math.floor(Math.random() * choices + lowerValue); 10 } 11 12 var num1 = selectFrom(1, 99); 13 var A = [] ; 14 A.push(num1) ; 15 for (var i = 1; i < 9; i++) { 16 var num2 = selectFrom(1, 99); 17 if (num2!==num1){ 18 A.push(num2) ; 19 } 20 }; 21 alert(A) ; 22 23 </script> 24 </head> 25 <body> 26 27 </body> 28 </html>
版权声明:本文为jl29233zx原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。