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

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

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

当前回答

这是JSLint的安全版本

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

其他回答

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

使用分治法的递归解:

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

这可能是最小的递归:-

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

ES-Next有很多方法

1. ES2015/ES6已经实现了这个repeat()方法!

/** * str: String * count: Number */ const str = `hello repeat!\n`, count = 3; let resultString = str.repeat(count); console.log(`resultString = \n${resultString}`); /* resultString = hello repeat! hello repeat! hello repeat! */ ({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2); // 'abcabc' (repeat() is a generic method) // Examples 'abc'.repeat(0); // '' 'abc'.repeat(1); // 'abc' 'abc'.repeat(2); // 'abcabc' 'abc'.repeat(3.5); // 'abcabcabc' (count will be converted to integer) // 'abc'.repeat(1/0); // RangeError // 'abc'.repeat(-1); // RangeError

2. ES2017/ES8新增String.prototype.padStart()

Const STR = 'abc '; Const times = 3; const newStr = str. padstartlength * times, str.toUpperCase()); console.log(' newStr = ', newStr); // "newStr =" "ABC ABC ABC "

3.ES2017/ES8新增String.prototype.padEnd()

Const STR = 'abc '; Const times = 3; const newStr = str. padend (str。length * times, str.toUpperCase()); console.log(' newStr = ', newStr); // "newStr =" "abc abc abc "

refs

http://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.repeat

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd

适用于所有浏览器

这是最简洁的:

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浏览器中运行。表中的数字指定了完全支持该方法的第一个浏览器版本: