Skip to content

Instantly share code, notes, and snippets.

@yedanbo
Last active June 18, 2021 02:36
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yedanbo/2229ecb275b57020209f to your computer and use it in GitHub Desktop.
Save yedanbo/2229ecb275b57020209f to your computer and use it in GitHub Desktop.
生成不重复的随机数函数(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