Skip to content

Instantly share code, notes, and snippets.

@xuanfeng
Last active December 8, 2019 09:37
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save xuanfeng/b23ab28ab412254e1594 to your computer and use it in GitHub Desktop.
Save xuanfeng/b23ab28ab412254e1594 to your computer and use it in GitHub Desktop.
产生任意长度随机字母数字组合
/*
** randomWord 产生任意长度随机字母数字组合
** randomFlag-是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
** xuanfeng 2014-08-28
*/
function randomWord(randomFlag, min, max){
var str = "",
range = min,
arr = ['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'];
// 随机产生
if(randomFlag){
range = Math.round(Math.random() * (max-min)) + min;
}
for(var i=0; i<range; i++){
pos = Math.round(Math.random() * (arr.length-1));
str += arr[pos];
}
return str;
}
// 方案二
// 指定具体位数
function getRandomStr(len) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < len; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
@sgshy1995
Copy link

111

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment