首页 > 代码库 > 如何选取10——99的5个随机数,并进行从小到大排序

如何选取10——99的5个随机数,并进行从小到大排序

function suiJi(startNum,endNum,item){  //startNum开始的数,endNum结束的数,item表示截取的数量

                   var compare = function(num1,num2){  //排序的方法

                   if(num1>num2){return 1;}

                   else if(num1<num2){return -1;}

                   else{return 0;}

                   }

                   var span = document.getElementsByClassName(‘span‘)[0];

                   btn.onclick =function(){

                   var member =[];

                   while(member.length<item){

                   var a = Math.floor(Math.random()*(endNum-startNum+1) + startNum); //生成的随机数

                   if(member.indexOf(a) == -1){

                            member.push(a);

                   }

         };

         span.innerHTML = member.sort(compare).join(‘|‘);

         }

         }

         suiJi(10,99,5);

总的来说就是这个样子的

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>随机数</title>

  <script type="text/javascript" src="http://www.mamicode.com/scripts/jquery-2.1.0.js"></script>

  <script type="text/javascript" src="http://www.mamicode.com/scripts/hmac-sha1.js"></script>

  <style>

  </style>

</head>

<body>

  <button>生成随机数</button>

  <span class="span"></span>

<script>

         function suiJi(startNum,endNum,item){

        

                   var compare = function(num1,num2){  //排序的方法

                   if(num1>num2){return 1;}

                   else if(num1<num2){return -1;}

                   else{return 0;}

                   }

                   var btn = document.querySelector(‘button‘);

                   var span = document.getElementsByClassName(‘span‘)[0];

                   btn.onclick =function(){

                   var member =[];

                   while(member.length<item){

                   var a = Math.floor(Math.random()*(endNum-startNum+1) + startNum); //生成的随机数

                   if(member.indexOf(a) == -1){

                            member.push(a);

                   }

         };

         span.innerHTML = member.sort(compare).join(‘|‘);

         }

         }

         suiJi(10,99,5);

</script>

</body>

</html>

需要web前端课程工具和电子书,可以加: 33群105601600(22群已满员,请关注新群)

【内容展示有限,可以加群下载,群文件会定期更新学习资料,以及练手小案例】

 

如何选取10——99的5个随机数,并进行从小到大排序