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

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

function repeat(s, n){
    var a = [];
    while(a.length < n){
        a.push(s);
    }
    return a.join('');
}

当前回答

使用数组(N + 1) . join(“string_to_repeat”)

其他回答

新读者注意:这个答案很老,而且不太实用——它只是“聪明”,因为它使用Array的东西来获取 串事情做完了。当我写“更少的过程”时,我肯定是指 “更少的代码”,因为,正如其他人在随后的回答中指出的那样,它 表演像猪一样。所以如果你看重速度就不要用它。

我将把这个函数直接放到String对象上。与其创建一个数组,填充它,然后用一个空字符连接它,不如创建一个适当长度的数组,然后用你想要的字符串连接它。同样的结果,更少的过程!

String.prototype.repeat = function( num )
{
    return new Array( num + 1 ).join( this );
}

alert( "string to repeat\n".repeat( 4 ) );

适用于所有浏览器

这是最简洁的:

function repeat(s, n) { return new Array(n+1).join(s); }

如果你也关心性能,这是一个更好的方法:

function repeat(s, n) { var a=[],i=0;for(;i<n;)a[i++]=s;return a.join(''); }

如果要比较这两个选项的性能,请参阅此Fiddle和此Fiddle以获得基准测试。在我自己的测试中,第二个选项在Firefox中大约快2倍,在Chrome中大约快4倍!

仅适用于现代浏览器:

在现代浏览器中,你现在也可以这样做:

function repeat(s,n) { return s.repeat(n) };

这个选项不仅比其他两个选项都要短,而且比第二个选项还要快。

不幸的是,它不能在任何版本的ie浏览器中运行。表中的数字指定了完全支持该方法的第一个浏览器版本:

好消息!String.prototype.repeat现在是JavaScript的一部分。

"yo".repeat(2);
// returns: "yoyo"

除Internet Explorer外,所有主流浏览器都支持该方法。有关最新列表,请参见MDN: String.prototype.repeat >浏览器兼容性。

MDN为没有支持的浏览器提供了一个填充。

我随机来到这里,从来没有理由在javascript中重复字符。

我对artistoex的做法印象深刻,对结果感到失望。我注意到最后一个串连接是不必要的,正如丹尼斯也指出的那样。

我注意到一些更多的东西,当玩抽样disfate放在一起。

The results varied a fair amount often favoring the last run and similar algorithms would often jockey for position. One of the things I changed was instead of using the JSLitmus generated count as the seed for the calls; as count was generated different for the various methods, I put in an index. This made the thing much more reliable. I then looked at ensuring that varying sized strings were passed to the functions. This prevented some of the variations I saw, where some algorithms did better at the single chars or smaller strings. However the top 3 methods all did well regardless of the string size.

分叉测试集

http://jsfiddle.net/schmide/fCqp3/134/

// repeated string
var string = '0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789';
// count paremeter is changed on every test iteration, limit it's maximum value here
var maxCount = 200;

var n = 0;
$.each(tests, function (name) {
    var fn = tests[name];
    JSLitmus.test(++n + '. ' + name, function (count) {
        var index = 0;
        while (count--) {
            fn.call(string.slice(0, index % string.length), index % maxCount);
            index++;
        }
    });
    if (fn.call('>', 10).length !== 10) $('body').prepend('<h1>Error in "' + name + '"</h1>');
});

JSLitmus.runAll();

然后我加入了丹尼斯的解决方案,并决定看看我是否能找到更多的方法。

由于javascript不能真正优化,提高性能的最好方法是手动避免一些东西。如果我把前4个琐碎的结果从循环中取出,我可以避免2-4个字符串存储,并将最后的存储直接写入结果。

// final: growing pattern + prototypejs check (count < 1)
'final avoid': function (count) {
    if (!count) return '';
    if (count == 1) return this.valueOf();
    var pattern = this.valueOf();
    if (count == 2) return pattern + pattern;
    if (count == 3) return pattern + pattern + pattern;
    var result;
    if (count & 1) result = pattern;
    else result = '';
    count >>= 1;
    do {
        pattern += pattern;
        if (count & 1) result += pattern;
        count >>= 1;
    } while (count > 1);
    return result + pattern + pattern;
}

这比丹尼斯的修复方案平均提高了1-2%。然而,不同的运行和不同的浏览器会显示相当大的差异,这额外的代码可能不值得在前面的两种算法上付出努力。

一个图表

编辑:我这样做主要是在chrome浏览器。Firefox和IE通常对Dennis的偏爱程度为百分之几。

基于数字连接字符串。

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

希望有帮助!