需求: 随机从35 个数中随机取出7个不相等的数; 可以查看历史记录
1. 方式1
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <input type="button" value="随机选择" id="input1"/> <div id="div1"></div> </body> <script> window.onload = function(){ var oBtn = document.getElementById(‘input1‘); var oDiv = document.getElementById(‘div1‘); var json = {};//映射关系用 oBtn.onclick = function(){ var num = Math.random(); var arr = randomNum(35, 7); json[num] = arr;//数组映射到json对象中 oDiv.innerHTML = arr; window.location.hash = num;//改变hash值 }; window.onhashchange = function(){ //http://localhost:63342/js/caipiao.html#0.4086829614825547 oDiv.innerHTML = json[window.location.hash.substring(1)];//去掉#号 } function randomNum(iAll, iNow){ var arr = []; var newArr = []; for(var i = 1; i <= iAll; i++){ arr.push(i);//1-35存到数组arr } for(var i = 0; i <= iNow; i++){ //取7个 var index = Math.floor(Math.random()*arr.length); newArr.push(arr.splice(index, 1));//每次根据下标剪切一个数到新数组中,所以永远不会重复 } return newArr; } } </script> </html>
方式二: 必须在服务器上写代码
<script> window.onload = function(){ var oBtn = document.getElementById(‘input1‘); var oDiv = document.getElementById(‘div1‘); oBtn.onclick = function(){ var arr = randomNum(35, 7); oDiv.innerHTML = arr; history.pushState(arr, ‘‘,Math.random()*100);//存数据, Math.random()*100王志发生变化,不要也可以 }; window.onpopstate = function(ev){ oDiv.innerHTML = ev.state;//取数据 } function randomNum(iAll, iNow){ var arr = []; var newArr = []; for(var i = 1; i <= iAll; i++){ arr.push(i);//1-35存到数组arr } for(var i = 0; i <= iNow; i++){ //取7个 var index = Math.floor(Math.random()*arr.length); newArr.push(arr.splice(index, 1));//每次根据下标剪切一个数到新数组中,所以永远不会重复 } return newArr; } } </script>
时间: 2024-11-11 18:20:17