repeatify js实现
repeatify js实现
在JavaScript中实现一个repeatify方法,可以将字符串重复指定次数。以下是几种实现方式:

使用原型扩展
String.prototype.repeatify = function(count) {
if (count < 0) throw new Error("Count must be non-negative");
return Array(count + 1).join(this);
};
调用方式:

console.log("hello".repeatify(3)); // 输出 "hellohellohello"
使用ES6的repeat方法
如果环境支持ES6,可以直接使用内置的repeat方法:
String.prototype.repeatify = function(count) {
return this.repeat(count);
};
使用循环拼接
String.prototype.repeatify = function(count) {
let result = '';
for (let i = 0; i < count; i++) {
result += this;
}
return result;
};
处理边界条件
String.prototype.repeatify = function(count) {
if (typeof count !== 'number' || count < 0) {
throw new Error("Invalid count value");
}
if (count === 0) return '';
return Array(count + 1).join(this);
};
以上方法均可实现字符串重复功能,根据实际需求选择适合的实现方式。






