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

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

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

当前回答

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

其他回答

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

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

这可能是最小的递归:-

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

这是JSLint的安全版本

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

如果您认为所有这些原型定义、数组创建和连接操作都是多余的,那么只需在需要的地方使用一行代码。字符串S重复N次:

for (var i = 0, result = ''; i < N; i++) result += 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:

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