Last active
June 18, 2021 02:36
-
-
Save yedanbo/2229ecb275b57020209f to your computer and use it in GitHub Desktop.
生成不重复的随机数函数(JS)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 生成随机数函数 | |
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