利用 String.fromCharCode() 配合 ASCII 碼範圍:
Math.floor(Math.random() * 26) + base/**
* 返回隨機小寫字母
*/
function getLowerCharacter() {
return String.fromCharCode(Math.floor(Math.random() * 26) + 'a'.charCodeAt(0));
}
/**
* 返回隨機大寫字母
*/
function getUpperCharacter() {
return String.fromCharCode(Math.floor(Math.random() * 26) + 'A'.charCodeAt(0));
}
/**
* 統一入口
* @param {'lower'|'upper'|'mixed'} type
*/
function getCharacter(type = 'mixed') {
const base = type === 'lower' ? 97 : type === 'upper' ? 65 : Math.random() < 0.5 ? 97 : 65;
return String.fromCharCode(Math.floor(Math.random() * 26) + base);
}
/**
* 生成指定長度的隨機字母字串
* @param {number} length
* @param {'lower'|'upper'|'mixed'} type
*/
function randomString(length = 8, type = 'mixed') {
let result = '';
const bases = {
lower: 97,
upper: 65,
mixed: null
};
for (let i = 0; i < length; i++) {
let base;
if (type === 'mixed') {
base = Math.random() < 0.5 ? 97 : 65;
} else {
base = bases[type];
}
result += String.fromCharCode(Math.floor(Math.random() * 26) + base);
}
return result;
}
// 使用
console.log(randomString(6, 'lower')); // 如 "kqjzpx"
console.log(randomString(10, 'upper')); // 如 "XKQJZPXWER"
console.log(randomString(16, 'mixed')); // 如 "aBcDeFgHiJkLmNoP"
// 利用 Array.from + 箭頭函數
const randomChar = (type = 'mixed') => {
const base = type === 'lower' ? 97 : type === 'upper' ? 65 : Math.random() < 0.5 ? 97 : 65;
return String.fromCharCode(Math.floor(Math.random() * 26) + base);
};
const randomString = (len = 8, type = 'mixed') =>
Array.from({ length: len }, () => randomChar(type)).join('');
// 一行版(僅大小寫混合)
const randStr = len => Array.from({ length: len }, () =>
String.fromCharCode(Math.floor(Math.random() * 52) + (Math.random() < 0.5 ? 65 : 71))
).join('');
| 方法 | 耗時 (ms) | 備註 |
|---|---|---|
| 基礎函數迴圈 | ~45 | 最穩定,易閱讀 |
| Array.from + map | ~52 | 函數式風格,略慢 |
| 預建字元池 + 隨機索引 | ~38 | 大量生成時最快 |
const POOL_LOWER = 'abcdefghijklmnopqrstuvwxyz';
const POOL_UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const POOL_MIXED = POOL_LOWER + POOL_UPPER;
function fastRandomString(len = 8, pool = POOL_MIXED) {
let s = '';
const max = pool.length - 1;
for (let i = 0; i < len; i++) {
s += pool[Math.floor(Math.random() * max)];
}
return s;
}
上述 Math.random() 為偽隨機,**不可用於 Token、密碼、加密金鑰** 生成。安全場景請使用 Web Crypto API:
async function secureRandomString(len = 16) {
const pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const arr = new Uint32Array(len);
window.crypto.getRandomValues(arr);
return Array.from(arr, x => pool[x % pool.length]).join('');
}
日常業務(驗證碼、臨時文件名、測試資料)用 Math.random() + 字元池足矣;涉及安全的場景**必須**使用 crypto.getRandomValues()。根據需求選擇合適的實現,兼顧可讀性與效能。