← 中文资源

简体中文版本

贪心换行填满每一行

贪心策略逐词装入当前行,放不下就断行换行且行尾不留多余空格:保证每一行都不超过宽度上限,适合终端表格、CLI 帮助文本与日志输出的定宽渲染。

阅读英文原文

运行结果

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

|The quick brown fox |
|jumps over a lazy   |
|dog near the river  |
|bank                |

实现说明

全部逻辑都在函数 wrap中。 结构是循环套循环:for (const word of text.split(/\s+/).filter(Boolean)) 在外,for (const line of wrapped) 在内。

常见问题

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。 文件在加载时定义 wrap。

主要签名是 function wrap(text, width)

核心语句

line += ' ' + word;

代码示例

// Greedy wrapping: take as many words as fit the width, then break.
// Words never split mid-word and lines never end with a stray space.
function wrap(text, width) {
  const lines = [];
  let line = '';
  for (const word of text.split(/\s+/).filter(Boolean)) {
    if (!line) {
      line = word;
    } else if (line.length + 1 + word.length <= width) {
      line += ' ' + word;
    } else {
      lines.push(line);
      line = word;
    }
  }
  if (line) lines.push(line);
  return lines;
}

const wrapped = wrap('The quick brown fox jumps over a lazy dog near the river bank', 20);
for (const line of wrapped) {
  console.log(`|${line.padEnd(20)}|`);
}