如何实现一个 repeat 方法?
参考答案
// 基础
function repeat(s, n) { return n > 0 ? new Array(n + 1).join(s) : ''; }
// 或直接用 String.prototype.repeat
手写(不依赖内置)
function repeat(str, n) {
if (n < 0) throw new RangeError('count must be non-negative');
let res = '', base = str, count = Math.floor(n);
while (count > 0) {
if (count & 1) res += base;
count >>= 1;
if (count) base += base; // 倍增,O(log n)
}
return res;
}
注意:n 为 Infinity/过大时抛 RangeError(结果超最大字符串长度);非整数需向下取整或报错。