js实现repeat
实现字符串重复功能
在JavaScript中实现字符串重复功能可以通过多种方式完成。以下是几种常见的方法:
使用String.prototype.repeat()方法
ES6引入了原生字符串重复方法,直接调用即可:
const repeatedStr = 'abc'.repeat(3); // 返回'abcabcabc'
使用数组和join方法
通过创建指定长度的数组并用目标字符串连接:
function repeat(str, count) {
return Array(count + 1).join(str);
}
使用循环拼接
基础循环实现方式:
function repeat(str, count) {
let result = '';
for (let i = 0; i < count; i++) {
result += str;
}
return result;
}
递归实现
递归方式实现重复:
function repeat(str, count) {
return count > 0 ? str + repeat(str, count - 1) : '';
}
性能优化版本
对于大量重复操作可使用二分法优化:
function repeat(str, count) {
let res = '';
while (count > 0) {
if (count % 2 === 1) res += str;
str += str;
count >>= 1;
}
return res;
}
实现函数重复执行
如果需要重复执行某个函数,可以采用以下方式:
基本循环调用
function repeat(fn, times) {
for (let i = 0; i < times; i++) fn();
}
使用setInterval实现间隔重复
function repeat(fn, times, interval) {
let count = 0;
const timer = setInterval(() => {
fn();
if (++count >= times) clearInterval(timer);
}, interval);
}
递归实现延迟重复

function repeat(fn, times, delay) {
if (times <= 0) return;
fn();
setTimeout(() => repeat(fn, times - 1, delay), delay);
}
这些实现方式覆盖了字符串重复和函数重复执行的不同场景,可以根据具体需求选择合适的方法。原生repeat方法在支持ES6的环境中最简洁高效,其他方法提供了更多自定义控制的可能性。






