谢谢!
------解决方案--------------------
for(i=0; i<30; i++) {
document.write(Math.floor(Math.random()*52) + '<br>');
}
------解决方案--------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript">
var a=[];
var b=[];
var i=0;
while(true){
var t=parseInt(Math.random()*52);
if(!a[t]){
a[t]=1;
b.push(t);
i++;
if(i==30){
break;
}
}
}
document.write(b);
</script>
</head>
<body>
</body>
</html>
------解决方案--------------------
function getDifNum(num,minNum,maxNum){
var res = [],
i=0,
len,
flag=false,
btn;
if(typeof maxNum != "number"){
maxNum = minNum;
minNum = 0;
}
if(maxNum <= minNum){
return;
}
btn = maxNum - minNum;
if(num >= btn){
return;
}else if(num > Math.ceil(btn/2)){
num = btn - num;
flag = true;
}
res = getRandArr(num,minNum,maxNum);
function getArr(num){
var arr = [],
i=0;
for(;i<num;i++){
arr[i] = i;
}
return arr;
}
function getRandArr(num,min,max){
var arr = [];
for(var i = 0;i<num;i++){
arr[i] = getRandNum(min,max);
}
return arr;
}
function getRandNum(min,max){
return Math.round(Math.random()*(max-min) + min)
}
function deleSame(arr){
var i=0;
arr.sort();
for(;i<arr.length;i++){
if(arr[i] == arr[i+1]){
arr.splice(i,1);
i--;
}
}
return arr;
}
function getOther(btn,arr){
var i=0,
len = arr.length;
var arr2 = getArr(btn),
btn = btn - arr.length;
for(i=0;i<len;i++){
arr2[arr[i]] = -1;
}
for(i=arr2.length-1;i>=0;i--){
if(arr2[i] == -1){
arr2.splice(i,1);
}
}
if(arr2.length > btn){
arr2 = arr2.slice(0,btn);
}
return arr2;
}
function checkInArr(num,arr){
for(var i=0,len=arr.length;i<len;i++){
if(arr[i] == num){
return true;
}
}
return false;
}
res = deleSame(res);
while(res.length < num){
var ran = getRandNum(minNum,maxNum);
if(!checkInArr(ran,res)){
res.push(ran);
};
}
if(res.length > num){
res = res.slice(0,num);
}
if(!flag){
return res;
}else{
return getOther(btn,res);
}
}
console.log(getDifNum(20,0,52));
------解决方案--------------------
var a = [];
for(var i = 0; i < 51; i++){
a.push(i);
}
a.sort(function(){return 0.5 - Math.random()});
a.length = 30;
console.log(a)
试试
------解决方案--------------------
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
var a = [];
for(var i = 0; i < 51; i++){
a.push(i);
}
function shuffle(obj,num){
var rand;
var index = 0;
var shuffled = [];
var i=0,len=obj.length;
if(typeof num =='undefined'){
num = len;
}
for(i;i<len&&i<num;i++){
rand = random(index++);
shuffled[index - 1] = shuffled[rand];
shuffled[rand] = obj[i];