实现说明
全部逻辑都在函数 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)}|`);
}