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));

转载于:https://www.cnblogs.com/yanjialin/p/11352626.html

你可能感兴趣的:(JS返回n位随机数)