第74天 写一个方法随机生成指定位数的字符串
Activity
DBTXf commentedon Jun 29, 2019
function getStringBylength(nlength) {
var str = "";
var 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'
];
for (var i = 0; i < nlength; i++) {
pos = Math.round(Math.random() * (arr.length - 1));
str += arr[pos];
}
return str
}
yujihu commentedon Jul 1, 2019
DusuWen commentedon Jul 2, 2019
DusuWen commentedon Jul 2, 2019
我这个方法不好,很容易Maximum call stack size exceeded
276259822 commentedon Jul 3, 2019
Kntt commentedon Jul 5, 2019
这个可以生成 0 - 12 位的随机字符串
Konata9 commentedon Jul 8, 2019
Vi-jay commentedon Jul 31, 2019
woodPeckerAnos commentedon Aug 12, 2019
/* 添加了一个随机字母大小写的功能 */
function randomCase (str) {
if (typeof str !== 'string') {
throw new TypeError('需要传入一个字符串')
}
const tempArr = []
for (let w of str) {
if (/\D/.test(w) && Math.random() * 10 < 5) {
tempArr.push(w.toUpperCase())
} else {
tempArr.push(w)
}
}
return tempArr.join('')
}
JJL-SH commentedon Oct 8, 2019
smile-2008 commentedon Jan 22, 2021
1684838553 commentedon Dec 9, 2021
dugufck666 commentedon Dec 29, 2021
不用递归的方式
xiaoqiangz commentedon Jun 21, 2022
function getRandomStr(num) {
return Array.from(new Array(num)).map(()=>{
// 取值 97 - 122区间小写子母
return String.fromCharCode(Math.floor(Math.random() * 26) + 97)
})
}
console.log(getRandomStr(10).join(''))