← 中文资源

简体中文版本

repeat 一次生成整段重复串

repeat 把单个字符放大成整条标尺:分隔线、缩进层级、进度条各一次调用完成,0 次重复自然得到空字符串,不用手写循环。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

----------------------------------------
STAGE 1: extract
----------------------------------------
node at depth 0
  node at depth 1
    node at depth 2
empty: ""
[###..] 3/5

实现说明

本示例的循环部分是 for (let depth = 0; depth < 3; depth++)。 顶层就这几处状态:ruler、done、total。

使用要点

  • 跑完文件,输出里会留下标记——STAGE 1: extract、empty:。

常见问题

包管理器会看到什么?

一份空的依赖清单。示例没有需要抓取的导入。 文件用顶层绑定保存自己的状态:ruler、done、total。

核心语句

const ruler = '-'.repeat(40);
const total = 5;
const done = 3;

代码示例

// repeat 把单个字符放大成整条视觉标尺,日志里的分隔线不用手写
const ruler = '-'.repeat(40);
console.log(ruler);
console.log('STAGE 1: extract');
console.log(ruler);

// repeat 也适合生成缩进层级:层级数乘出来,不写循环
for (let depth = 0; depth < 3; depth++) {
  console.log('  '.repeat(depth) + 'node at depth ' + depth);
}

// 零次 repeat 是空字符串,边界自然成立
console.log('empty:', JSON.stringify('-'.repeat(0)));

// 与字符串拼接组合:把进度条画到指定刻度
const done = 3;
const total = 5;
console.log('[' + '#'.repeat(done) + '.'.repeat(total - done) + '] ' + done + '/' + total);