repeatify js实现
实现 repeatify 方法
repeatify 是一个自定义的字符串方法,用于将字符串重复指定次数。以下是实现方法:

String.prototype.repeatify = function(count) {
if (count < 0) throw new Error('Count must be non-negative');
if (count === 0) return '';
return Array(count).fill(this).join('');
};
使用示例
console.log('hello'.repeatify(3)); // 输出: hellohellohello
console.log('abc'.repeatify(0)); // 输出: (空字符串)
注意事项
- 方法直接扩展了 JavaScript 的
String.prototype,可能会与其他库冲突 - 包含基本的错误检查,当
count为负数时抛出错误 - 使用
Array.fill和join实现,性能较好
替代实现方式
如果不希望修改原型,可以使用函数形式:

function repeatify(str, count) {
return count <= 0 ? '' : Array(count).fill(str).join('');
}
浏览器兼容性
对于旧版浏览器,可能需要 polyfill Array.fill 方法,或使用传统循环实现:
String.prototype.repeatify = function(count) {
var result = '';
for (var i = 0; i < count; i++) {
result += this;
}
return result;
};






