// 生成随机密码
function generateRandomPassword(length, includeUpperCase, includeLowerCase, includeNumbers, includeSymbols) {
// 定义字符集合
let charset = '';
if (includeUpperCase) charset += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (includeLowerCase) charset += 'abcdefghijklmnopqrstuvwxyz';
if (includeNumbers) charset += '0123456789';
if (includeSymbols) charset += '!@#$%^&*()_+-=[]{}|;:,.<>?';
if (charset.length === 0) {
console.error('请至少选择一种字符类型。');
return null;
}
let password = '';
for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * charset.length);
password += charset[randomIndex];
}
return password;
}
// 使用示例
const length = 12; // 密码长度
const password = generateRandomPassword(length, true, true, true, true); // 包含大写字母、小写字母、数字和特殊字符
console.log('生成的随机密码为:', password);
这段代码定义了一个名为 generateRandomPassword
的函数,接受五个参数:
length
:生成的密码长度includeUpperCase
:是否包含大写字母includeLowerCase
:是否包含小写字母includeNumbers
:是否包含数字includeSymbols
:是否包含特殊字符
函数根据参数的设定,生成符合要求的随机密码并返回。密码生成过程中,通过随机选择字符集合中的字符来构建密码。