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

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

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

当前回答

新读者注意:这个答案很老,而且不太实用——它只是“聪明”,因为它使用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浏览器中运行。表中的数字指定了完全支持该方法的第一个浏览器版本:

基于数字连接字符串。

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

希望有帮助!

扩展P.Bailey的解决方案:

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

这样你就可以避免意外的参数类型:

var foo = 'bar';
alert(foo.repeat(3));              // Will work, "barbarbar"
alert(foo.repeat('3'));            // Same as above
alert(foo.repeat(true));           // Same as foo.repeat(1)

alert(foo.repeat(0));              // This and all the following return an empty
alert(foo.repeat(false));          // string while not causing an exception
alert(foo.repeat(null));
alert(foo.repeat(undefined));
alert(foo.repeat({}));             // Object
alert(foo.repeat(function () {})); // Function

编辑:感谢jerone为他优雅的++num想法!

这个很有效

String.prototype.repeat = function(times){
    var result="";
    var pattern=this;
    while (times > 0) {
        if (times&1)
            result+=pattern;
        times>>=1;
        pattern+=pattern;
    }
    return result;
};

小提琴:http://jsfiddle.net/3Y9v2/

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