Skip to content

Instantly share code, notes, and snippets.

@yedanbo
Last active Jun 18, 2021
Embed
What would you like to do?
生成不重复的随机数函数(JS)
// 生成随机数函数
function createRandom(num,from,to)
{
var arr=[]; // 随机数数组
var json={}; // 标记json对象
while(arr.length<num)
{
// 产生单个随机数
var ranNum=Math.round(Math.random()*(to-from))+from;
// 通过判断json对象的索引值是否存在 来标记 是否重复
if(!json[ranNum])
{
json[ranNum]=1;
arr.push(ranNum); // 将生成的不重复随机数存入数组
}
}
return arr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment