返回任意次数的字符串的最佳或最简洁的方法是什么?

以下是我目前为止拍得最好的照片:

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;}

其他回答

这是JSLint的安全版本

String.prototype.repeat = function (num) {
  var a = [];
  a.length = num << 0 + 1;
  return a.join(this);
};

这可能是最小的递归:-

String.prototype.repeat = function(n,s) {
s = s || ""
if(n>0) {
   s += this
   s = this.repeat(--n,s)
}
return s}

我已经测试了所有提议的方法的性能。

这是我找到的最快的变种。

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:

如果可以的话,使用它,让它更快:)

使用分治法的递归解:

function repeat(n, s) {
    if (n==0) return '';
    if (n==1 || isNaN(n)) return s;
    with(Math) { return repeat(floor(n/2), s)+repeat(ceil(n/2), s); }
}

基于数字连接字符串。

function concatStr(str, num) {
   var arr = [];

   //Construct an array
   for (var i = 0; i < num; i++)
      arr[i] = str;

   //Join all elements
   str = arr.join('');

   return str;
}

console.log(concatStr("abc", 3));

希望有帮助!