const getRandomChar = (len, type) => {
// 生成随机数
function getChar (chars) {
return chars.charAt(Math.floor(Math.random() * chars.length))
}
let charsNum = '0123456789'
let charsString = 'qwertyuiopasdfghjklzxcvbnm'
let chars = '0123456789qwertyuiopasdfghjklzxcvbnm'
let result = ''
let useChars = ''
if (type === 'string') {
useChars = charsString
} else if (type === 'number') {
useChars = charsNum
} else {
useChars = chars
}
while (len--) {
result += getChar(useChars)
}
return result
}
//调用的时候需要注意,如要生成纯string或者number的话,需要在后面加多 'string'/'number',千亩安的数字意义为长度,如果没有加多后面的话是默认string+number的随机数(多用于随机登录账号/密码)
this.getRandomChar(5,'string')
H5 js生成随机数封装
最新推荐文章于 2023-06-27 16:30:10 发布
该博客介绍了JavaScript中用于生成随机字符串或数字的函数。通过指定类型和长度,函数能够生成不同类型的随机字符序列,适用于创建随机密码或账号。在调用时需注意指定字符串'string'或'number'以确保生成指定类型的序列。
摘要由CSDN通过智能技术生成