返回任意次数的字符串的最佳或最简洁的方法是什么?
以下是我目前为止拍得最好的照片:
function repeat(s, n){
var a = [];
while(a.length < n){
a.push(s);
}
return a.join('');
}
返回任意次数的字符串的最佳或最简洁的方法是什么?
以下是我目前为止拍得最好的照片:
function repeat(s, n){
var a = [];
while(a.length < n){
a.push(s);
}
return a.join('');
}
当前回答
function repeat(s, n) { var r=""; for (var a=0;a<n;a++) r+=s; return r;}
其他回答
使用Lodash来实现Javascript的实用功能,比如重复字符串。
Lodash提供了良好的性能和ECMAScript兼容性。
我强烈推荐它用于UI开发,它在服务器端也很好用。
下面是如何使用Lodash重复字符串“yo”2次:
> _.repeat('yo', 2)
"yoyo"
简单的方法:
String.prototype.repeat = function(num) {
num = parseInt(num);
if (num < 0) return '';
return new Array(num + 1).join(this);
}
/**
@desc: repeat string
@param: n - times
@param: d - delimiter
*/
String.prototype.repeat = function (n, d) {
return --n ? this + (d || '') + this.repeat(n, d) : '' + this
};
这是如何重复字符串多次使用delimeter。
好消息!String.prototype.repeat现在是JavaScript的一部分。
"yo".repeat(2);
// returns: "yoyo"
除Internet Explorer外,所有主流浏览器都支持该方法。有关最新列表,请参见MDN: String.prototype.repeat >浏览器兼容性。
MDN为没有支持的浏览器提供了一个填充。
我已经测试了所有提议的方法的性能。
这是我找到的最快的变种。
String.prototype.repeat = function(count) {
if (count < 1) return '';
var result = '', pattern = this.valueOf();
while (count > 1) {
if (count & 1) result += pattern;
count >>= 1, pattern += pattern;
}
return result + pattern;
};
或作为独立函数:
function repeat(pattern, count) {
if (count < 1) return '';
var result = '';
while (count > 1) {
if (count & 1) result += pattern;
count >>= 1, pattern += pattern;
}
return result + pattern;
}
它基于wnrph算法。 它真的很快。与传统的Array(count + 1).join(string)方法相比,计数越大,它的运行速度就越快。
我只改变了两件事:
replace pattern = this with pattern = this. valueof()(清除一个明显的类型转换); 增加if (count < 1)检查从prototypejs到函数的顶部,以排除在这种情况下不必要的操作。 应用优化从丹尼斯的答案(5-7%的速度提高)
UPD
为感兴趣的人准备了一个性能测试场地。
变量计数~ 0 ..100:
常量= 1024:
如果可以的话,使用它,让它更快:)