JavaScript 从大小写字母和数字自动生成X位密码
核心代码
function generatePassword() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let password = '';
for (let i = 0; i < 8; i++) {
const randomIndex = Math.floor(Math.random() * chars.length);
password += chars[randomIndex];
}
return password;
}
知识点
Math.random() 能生成一个随机浮点数X,X的范围在0-1之间()
利用 Math.random() 生成随机数常用示例:
范围
Math.floor(Math.random() * M)
范围
Math.floor(Math.random() * (M+1))
范围
Math.floor(Math.random() * (M - N) + N)
范围
Math.floor(Math.random() * (M - N + 1) + N)