12345678910111213141516171819202122232425262728293031 |
- /**
- * 生成指定长度的随机数字字母组合(确保同时包含字母和数字)
- * @param {number} length 要生成的字符串长度
- * @returns {string} 随机生成的字符串
- */
- function generateRandomCode(length = 6) {
- const numbers = '0123456789';
- const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
- const chars = numbers + letters;
-
- // 确保至少包含 1 个数字和 1 个字母
- let result = [];
- result.push(numbers.charAt(Math.floor(Math.random() * numbers.length))); // 随机一个数字
- result.push(letters.charAt(Math.floor(Math.random() * letters.length))); // 随机一个字母
- // 生成剩余的字符
- for (let i = 2; i < length; i++) {
- result.push(chars.charAt(Math.floor(Math.random() * chars.length)));
- }
- // **打乱数组顺序(Fisher-Yates 洗牌算法,更高效)**
- for (let i = result.length - 1; i > 0; i--) {
- const j = Math.floor(Math.random() * (i + 1));
- [result[i], result[j]] = [result[j], result[i]];
- }
- return result.join('');
- }
- module.exports = {
- generateRandomCode
- }
|