实现说明
repeat 复制字符串并拒绝坏参数以函数 indent为骨架。
使用要点
- 直接运行文件,输出会带上标签,比如
ab、negative:、infinity:——输出的每一行都能指回产生它的那次调用。
常见问题
在一个没有任何依赖声明的空项目里能跑吗?
可以——空项目原样能跑,因为什么都不用声明。 文件在加载时定义 indent。
入口签名:function indent(level, text)
核心语句
return " ".repeat(level) + text;
代码示例
// repeat 复制字符串 n 次
console.log("ab".repeat(3));
console.log("-".repeat(10));
// 0 次返回空串,负数或 Infinity 抛 RangeError
console.log("x".repeat(0) === "");
try {
"x".repeat(-1);
} catch (e) {
console.log("negative:", e.name);
}
try {
"x".repeat(Infinity);
} catch (e) {
console.log("infinity:", e.name);
}
// 实际用途:缩进与分隔线
function indent(level, text) {
return " ".repeat(level) + text;
}
console.log(indent(2, "nested item"));
// 构建固定宽度分隔符
const width = 20;
console.log("+".repeat(width + 2));