const randomHexColor = () =>
'#' + Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0');
// 使用
console.log(randomHexColor()); // "#3a7f2e"
var getRandomColor = function(color) {
return (color += '0123456789abcdef'[Math.floor(Math.random()*16)])
&& (color.length == 6) ? color : arguments.callee(color);
}(''); // 立即呼叫,傳入空字串啟動
原理:遞迴累加 6 個十六進位字元,長度達 6 即回傳。
function randomColorLoop() {
var hex = '0123456789abcdef', color = '#';
for (var i = 0; i < 6; i++) color += hex[Math.random() * 16 | 0];
return color;
}
crypto.getRandomValues(密碼學級隨機,安全場景)function secureRandomColor() {
var arr = new Uint32Array(1);
crypto.getRandomValues(arr);
return '#' + arr[0].toString(16).padStart(6, '0').slice(-6);
}
| 方法 | 耗時 (ms) | 備註 |
|---|---|---|
| 迴圈版 | ~45 | 最快,無函式呼叫開銷 |
| ES6 padStart | ~65 | 可讀性最佳,現代瀏覽器支援 |
| 遞迴版 | ~120 | 函式呼叫開銷大,不建議大量使用 |
| crypto 版 | ~200 | 安全隨機,非一般 UI 需求 |
['#e74c3c', '#3498db', ...] 取模索引。const randomRGB = () => `rgb(${Math.random()*255|0}, ${Math.random()*255|0}, ${Math.random()*255|0})`;
const randomHSL = () => `hsl(${Math.random()*360|0}, ${50+Math.random()*50|0}%, 50%)`;