您的位置:首页 > 其它

给字符串对象定义一个repeat功能。当传入一个整数n时,它会返回重复n次字符串的结果。

2017-12-06 13:50 519 查看
比如console.log("html".repeat(3));会得到htmlhtmlhtml。

知识点解释:JavaScript继承和prototype的知识点。

举例:

String.prototype.repeat = String.prototype.repeat || function (times) {
var string = '';
for (var i = 0; i < times; i++) {
string += this; // this的值为调用此方法的字符串
}
return string;
}
console.log('html'.repeat(3));

这里的另一个要点是,你要知道如何不覆盖可能已经定义的功能。通过测试一下该功能定义之前并不存在: 

String.prototype.repeat = String.prototype.repeat || function(times) {/* code here */};


当你被要求做好JavaScript函数兼容时这种技术特别有用。 

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐