用 String.prototype.repeat 可高效生成动态加载进度条,通过重复字符(如 █/░)模拟填充效果,结合定时器实现平滑动画,并支持多风格占位符切换;需注意兼容性及参数安全校验。
用 String.prototype.repeat 生成加载进度条的动态占位符,核心是用重复字符(如 █、■ 或 .)模拟“逐步填充”效果,配合定时器或异步状态更新即可实现简洁又可控的视觉反馈。
假设进度条总长 20 个字符,当前完成度为 65%,则应显示 13 个实心块(Math.floor(20 * 0.65) === 13):
const totalWidth = 20;const percent = 0.65;const filledCount = Math.floor(totalWidth * percent);const bar = '█'.repeat(filledCount) + '░'.repeat(totalWidth - filledCount);console.log(`[${bar}] ${Math.round(percent * 100)}%`); // → [█████████████░░░░░] 65%
不用第三方库,仅靠 repeat + setTimeout 就能做出渐进式加载条:
repeat 拼出已填充部分和未填充部分process.stdout.write(Node.js)或 console.log(浏览器调试时可用 innerText 更新 DOM 元素)刷新显示function animateProgress(target = 100, frames = 30) { let current = 0; const interval = setInterval(() => { current = Math.min(target, current + target / frames); const filled = '█'.repeat(Math.floor(current / 5)); // 每 5% 占 1 个 █(20格满) const empty = '░'.repeat(20 - Math.floor(current / 5)); process.stdout.write(`r[${filled}${empty}] ${Math.round(current)}%`); if (current >= target) clearInterval(interval); }, 100);}
根据 UI 风格灵活切换字符组合,repeat 让替换成本极低:
'='.repeat(12) + '>' → ============>
'•'.repeat(8) + '◦'.repeat(12) → ••••••••◦◦◦◦◦◦◦◦◦◦◦◦
'#'.repeat(5) + '-'.repeat(15) → #####---------------
关键在于把“已加载部分”和“待加载部分”拆成两个独立字符串,再用 repeat 控制各自长度,无需拼接循环。
String.prototype.repeat 在现代浏览器和 Node.js 4+ 中原生支持,若需兼容旧环境(如 IE),可加简单 polyfill:
if (!String.prototype.repeat) { String.prototype.repeat = function(count) { return Array(count + 1).join(this); };}
另外注意:传入负数、Infinity 或过大的数会抛错,建议对 count 做安全校验,例如 Math.max(0, Math.min(100, count))。