JS返回n位随机数

function generateMixed(n) {
var count = n+1;
var res = "";
for(var i = 0; i <= 10000; i++) {
var id = parseInt(Math.random() * count);
var index = res.indexOf(id);
if(index == -1){
res += id;
}
if(res.length == count){
break;
}
}
return res;
}

//console.log(generateMixed(8));


function generateMixed2(n) {
var str = "";
function num(n) {
var id = parseInt(Math.random() * (n+1));
var index = str.indexOf(id);
if(index == -1){
str += id;
}
if(str.length < n+1){
num(n);
}
}
num(n);
return str;
}

console.log(generateMixed2(5));

posted @ 2019-08-14 16:06  天外小龙虾  阅读(673)  评论(0编辑  收藏  举报