关于获取随机数字的练习
1 所选取数字的最大数字:<input type="number" id="max_num"><br> 2 所选取数字的最小数字:<input type="number" id="min_num"><br> 3 需要选取的个数:<input type="number" id="howMany"><br> 4 获得的随机数字:<p id="getRandomNumber"></p><br> 5 <input type="button" value="点击获取随机数" id="btn"><br> 6 <script> 7 var randomNumberArray = function () { 8 var n = parseInt(document.getElementById("howMany").value); 9 var minNum = parseInt(document.getElementById("min_num").value); 10 var maxNum = parseInt(document.getElementById("max_num").value); 11 var randomNumArr = []; 12 for (var i = 0; i < n; i++) { 13 var randomNum = (Math.floor(Math.random() * (maxNum - minNum + 1))) + minNum; 14 while (randomNumArr.indexOf(randomNum) != -1) { 15 randomNum = (Math.floor(Math.random() * (maxNum - minNum + 1))) + minNum; 16 } 17 randomNumArr.push(randomNum); 18 } 19 return randomNumArr.sort(function (value1, value2) { 20 return value1 - value2; 21 }) 22 } 23 24 var getNumAndShowThem = function () { 25 document.getElementById("getRandomNumber").innerHTML = randomNumberArray(); 26 } 27 document.getElementById("btn").addEventListener("click", getNumAndShowThem);
实现功能:
1.根据指定的区间以及指定的获取数字个数来获得随机数字。
2.所有随机数字不相同且按从小到大顺序排列。