JS生成不重复的随机序列号


 1 function getRandomCode(length) {
 2   if (length > 0) {
 3     var data = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
 4     var nums = "";
 5     for (var i = 0; i < length; i++) {
 6       var r = parseInt(Math.random() * 61);
 7       nums += data[r];
 8     }
 9     return nums;
10   } else {
11     return false;
12   }
13 }
14 var res = getRandomCode(32);
15 console.log(res);

 length参数为生成随机序列号的字符长度;

Math.random(),返回介于 0(包含) ~ 1(不包含) 之间的一个随机数。

    取得介于 1 到 10 之间的一个随机数:Math.floor((Math.random()*10)+1);

    取得介于 1 到 100 之间的一个随机数:Math.floor((Math.random()*100)+1);

    取得min(包含)~ max(不包含)之间的数字:Math.floor(Math.random() * (max - min) ) + min;

    取得min(包含)~ max(包含)之间的数字:Math.floor(Math.random() * (max - min + 1) ) + min;


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM