js 生成8位随机数,必须包含大写字母,小写字母和数字。
方式一:
有漏洞的
1 function generateRandomString() { 2 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 3 var randomString = ""; 4 for (var i = 0; i < 8; i++) { 5 var randomIndex = Math.floor(Math.random() * chars.length); 6 randomString += chars.charAt(randomIndex); 7 } 8 return randomString; 9 } 10 var randomString = generateRandomString(); 11 console.log(randomString);
方式二:
不完美,可以再将字符打乱。
1 function generateRandomString() { 2 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 3 var uppercaseChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 4 var lowercaseChar = "abcdefghijklmnopqrstuvwxyz"; 5 var numberChar = "0123456789"; 6 var randomString = ""; 7 //首先从每个字符集中选择一个字符 8 randomString += uppercaseChar.charAt(Math.floor(Math.random() * uppercaseChar.length)); 9 randomString += lowercaseChar.charAt(Math.floor(Math.random() * lowercaseChar.length)); 10 randomString += numberChar.charAt(Math.floor(Math.random() * numberChar.length)); 11 //随机选择其他字符 12 for (var i = 3; i < 8; i++) { 13 var randomIndex = Math.floor(Math.random() * chars.length); 14 randomString += chars.charAt(randomIndex); 15 } 16 //对字符串进行随机排序 17 randomString = randomString.split('').sort(function(){ 18 return 0.5-Math.random(); 19 }).join(''); 20 return randomString; 21 } 22 //测试代码 23 console.log(generateRandomString());
// 最后,为确保生成的字符串具有随机性,使用split()
方法将字符串转换为字符数组,再将此数组随机排序,并使用join()
方法将排序后的字符重新组成一个字符串。这种方法可以防止字符选择过于一致,从而增强随机性。
方式三:
感觉还是有漏洞
1 function generateRandomString() { 2 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 3 var length = 8; 4 var result = ""; 5 var hasUpperCase = false; 6 var hasLowerCase = false; 7 var hasNumber = false; 8 for (var i = 0; i < length; i++) { 9 var randomChar = chars.charAt(Math.floor(Math.random() * chars.length)); 10 result += randomChar; 11 if ("ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(randomChar) != -1) { 12 hasUpperCase = true; 13 } else if ("abcdefghijklmnopqrstuvwxyz".indexOf(randomChar) != -1) { 14 hasLowerCase = true; 15 } else if ("0123456789".indexOf(randomChar) != -1) { 16 hasNumber = true; 17 } 18 } 19 if (hasUpperCase && hasLowerCase && hasNumber) { 20 return result; 21 } else { 22 return generateRandomString(); 23 } 24 }
1 function generateRandomString() { 2 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 3 var uppercase = false, lowercase = false, digit = false; 4 var randomStr = ''; 5 while (!(uppercase && lowercase && digit) || randomStr.length < 8) { 6 var randomNum = Math.floor(Math.random() * chars.length); 7 randomStr += chars.substring(randomNum, randomNum + 1); 8 uppercase = /[A-Z]/.test(randomStr); 9 lowercase = /[a-z]/.test(randomStr); 10 digit = /\d/.test(randomStr); 11 } 12 return randomStr; 13 }