利用JavaScript生成随机数字!

 <!DOCTYPE html>
<html>
<head>
<title>1-99的随机数字</title>
<script type="text/javascript"> function selectFrom(lowerValue, upperValue) {
var choices = upperValue - lowerValue + 1;
return Math.floor(Math.random() * choices + lowerValue);
} var num = selectFrom(1, 99);
alert(num); //number between 1 and 99 </script>
</head>
<body> </body>
</html>

本例中使用了Math对象的Math.floor()方法以及random()方法!

那么我要生成1到99范围内9个不重复的数字,而且以数组形式输出呢?

 <!DOCTYPE html>
<html>
<head>
<title>不重复的9个属于1-99的随机数字</title>
<script type="text/javascript"> function selectFrom(lowerValue, upperValue) {
var choices = upperValue - lowerValue + 1;
return Math.floor(Math.random() * choices + lowerValue);
} var num1 = selectFrom(1, 99);
var A = [] ;
A.push(num1) ;
for (var i = 1; i < 9; i++) {
var num2 = selectFrom(1, 99);
if (num2!==num1){
A.push(num2) ;
}
};
alert(A) ; </script>
</head>
<body> </body>
</html>
上一篇:android控制之 adb shell (已完成,不定期增加内容)


下一篇:Golang微服务:Micro限流、熔断