<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS创建随机产生一组数据</title>
<!-- <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> -->
</head>
<body>
<input type="button" id="ip1" value="创建数组">
<input type="button" id="ip2" value="创建数组(setInterval)">
<button>清除变化</button>
<p id="str"></p>
<p id="str1"></p>
<script type="text/javascript">
var ipt1=document.getElementById("ip1");
var ipt2=document.getElementById("ip2");
var wr1=document.getElementById("str");
var wr2=document.getElementById("str1");
var btn=document.getElementsByTagName("button");
function MathRand(m,n){//m为随机数长度,n为需要的个数m>=n
var str=[];
var num=[];
var txt="";
for (var i = 0; i < m; i++)
{
str.push(i);//创建空数组,存放一组数据m=10为0-9
}
wr1.innerHTML="创建随机数数组长度: "+m+"</br>"+"数组为: "+str+"<hr>";
for(var i = m; i > 0; i--)//m改为n则n为需要的随机数个数
{
var x=Math.floor(Math.random()*i);//随机产生一个0-i之间的数字
var r=str[x];//获取数组中的一个值
var y = str.splice(x,1);//将这个值从数组剪切出来
num.push(y);//并添加到另一个数组中
txt += "数组长度: "+i+"</br>"
+"random随机数: "+x+"</br>"
+"去除随机数数组为: "+str+"</br>"
+"获取的随机数为: "+r+"</br>"
+"截取的数组: "+num+"</br>"+"<hr>";//输出数组
}
wr2.innerHTML=txt+"</br>";
}
function compare(a,b){return a-b;}
function setA(){
cle = setInterval("MathRand(20,10)",1000);
}
function clearA(){
clearInterval(cle);
}
function addHandler(element, type, handler){
if (element.addEventListener){
element.addEventListener(type, handler, false);
} else if (element.attachEvent){
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler;
}
}
//MathRand(20,0);
addHandler(ipt1,"click",function(){MathRand(20,1)});//绑定传参函数
addHandler(ipt2,"click",setA);
addHandler(btn[0],"click",clearA);
</script>
</body>
</html>