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

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

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

当前回答

disfated的答案提高了5-7%。

通过在计数> 1处停止来展开循环,并在循环之后执行额外的result += pattnern concat。这将避免循环最终使用以前未使用的模式+=模式,而不必使用昂贵的if检查。 最终的结果是这样的:

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;
    }
    result += pattern;
    return result;
};

下面是disfate的小提琴分叉的展开版本:http://jsfiddle.net/wsdfg/

其他回答

这是JSLint的安全版本

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

要在指定次数内重复一个字符串,可以使用JavaScript中内置的repeat()方法。

下面是一个重复以下字符串4次的例子:

const name = "king";

const repeat = name.repeat(4);

console.log(repeat);

输出:

"kingkingkingking"

或者我们可以创建自己版本的repeat()函数,如下所示:

function repeat(str, n) {
  if (!str || !n) {
    return;
  }

 let final = "";
  while (n) {
    final += s;
    n--;
  }
  return final;
}

console.log(repeat("king", 3))

(最初发布于https://reactgo.com/javascript-repeat-string/)

人们将这一问题过于复杂,甚至浪费了表现。数组?递归?你在跟我开玩笑吧。

function repeat (string, times) {
  var result = ''
  while (times-- > 0) result += string
  return result
}

编辑。我做了一些简单的测试,与artistoex / disfated和其他一些人发布的按位版本进行比较。后者只是稍微快一点,但内存效率高了几个数量级。对于单词'blah'的1000000次重复,使用简单的串联算法(上面),Node进程的容量达到46兆字节,而使用对数算法只有5.5兆字节。后者绝对是正确的选择。为了清晰起见,我将其转发:

function repeat (string, times) {
  var result = ''
  while (times > 0) {
    if (times & 1) result += string
    times >>= 1
    string += string
  }
  return result
}

扩展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想法!