function randomString (count, length) {
let resultList = []
let charList = genCharList()
let charNum = charList.length
let i = 0
while (i < count) {
let lst = genRandomNum(charNum, length) // 随机列表下标
if (!lst) return
let randomCharList = lst.map(j => charList[j])
let str = randomCharList.join('')
if (resultList.includes(str)) continue
resultList.push(str)
i++
}
return resultList
}
function genCharList () { // 生成所有字符列表,包含大小写字母、数字
let lst = []
for (let i = 0; i < 26; i++) {
let lower = String.fromCodePoint(i + 97)
let upper = String.fromCodePoint(i + 65)
lst.push(lower, upper)
}
for (let i = 0; i < 10; i++) {
lst.push(`${i}`)
}
return lst
}
function genRandomNum (top, count) { // 生成count个 0~top的不重复数字
if (top < count) return null
let lst = []
for (let i = 0; i < count; i++) {
let num = Math.floor(Math.random() * top)
while (lst.includes(num)) {
num = Math.floor(Math.random() * top)
}
lst.push(num)
}
return lst
}
console.log(randomString(5, 6)) // 生成5个长度为6的不同随机串
没什么难度吧? 生成所有字符的列表,生成0~列表长度内不重复的6个随机数,取出对应的列表元素组成字符串str,这是一次生成,判断有重复str,再生成一次。
练练手写了一下:
输出:
建议多思考,这个问题很简单的~