日期:2014-05-16 浏览次数:20363 次
<script type="text/javascript"> var seeds = [1,2,3,4,5,6,7,8,9,10]; var getRand = function () { if(seeds.length == 0){ alert("没了"); return; } var rand = Math.ceil(Math.random()*seeds.length); var result = seeds[rand-1]; seeds.splice(rand-1,1); return result; }; </script> <input type="button" value="" onclick="getRand()" />
------解决方案--------------------
JS有着强大的数组操作函数 例如push()pop()
思路就是用数组来实现 例如数组a初始10个值,分别是1~10,然后进行4次循环 每次循环从数组长度中随机获取一个位置值n,然后输出a[n],接着用splice把当前位置的数组元素删除,接着进行下一次循环,直到循环结束
代码如下,请放在<body></body>标签中测试
<script language="javascript">
var a=Array(,1,2,3,4,5,6,7,8,9,10); for (var i=0;i<4;i++){ b=parseInt(a.length*Math.random()); document.write("time"+(i+1)+"="+a[b]+"<br>"); a.splice(b,1); }
------解决方案--------------------
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<script type="text/javascript">
function GetRandomNum(Min, Max) {
var Range = Max - Min;
var Rand = Math.random();
return (Min + Math.round(Rand * Range));
}
Array.prototype.remove = function (dx) {
if (isNaN(dx) || dx > this.length) { return false; }
for (var i = 0, n = 0; i < this.length; i++) {
if (this[i] != this[dx]) {
this[n++] = this[i]
}
}
this.length -= 1
}
var number = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var str = [];
for (var i = 0; i < 4; i++) {
var j = GetRandomNum(1, 10-i);
str[i] = number[j];
number.remove(j);
}
alert(str);
</script>
<body>
</body>