在Perl中,我可以使用以下语法多次重复一个字符:

$a = "a" x 10; // results in "aaaaaaaaaa"

有没有一种简单的方法在Javascript中实现这一点?我显然可以使用一个函数,但我想知道是否有内置的方法,或者其他一些巧妙的技术。


当前回答

我意识到这不是一个流行的任务,如果你需要重复字符串而不是整数次呢?

使用repeat()和slice()是可能的,下面是方法:

String.prototype.fracRepeat = function(n){
  if(n < 0) n = 0;
  var n_int = ~~n; // amount of whole times to repeat
  var n_frac = n - n_int; // amount of fraction times (e.g., 0.5)
  var frac_length = ~~(n_frac * this.length); // length in characters of fraction part, floored
  
  return this.repeat(n) + this.slice(0, frac_length);
}

以下是一个简短的版本:

String.prototype.fracRepeat=函数(n){如果(n<0)n=0;返回this.repeat(n)+this.slice(0,~~((n-~n)*this.length));}var s=“abcd”;console.log(s.fracRepeat(2.5))

其他回答

另一种选择是:

for(var word = ''; word.length < 10; word += 'a'){}

如果需要重复多个字符,请乘以条件:

for(var word = ''; word.length < 10 * 3; word += 'foo'){}

注意:您不必像word=Array(11)那样超出1。join('a')

适用于所有浏览器

以下功能的执行速度比公认答案中建议的选项快得多:

var repeat = function(str, count) {
    var array = [];
    for(var i = 0; i < count;)
        array[i++] = str;
    return array.join('');
}

你可以这样使用:

var repeatedString = repeat("a", 10);

要将此功能的性能与公认答案中提出的选项的性能进行比较,请参阅本基准和本基准。

仅适用于现代浏览器

在现代浏览器中,您现在可以使用String.prototype.repeat方法执行此操作:

var repeatedString = "a".repeat(10);

阅读有关MDN上此方法的更多信息。

这个选项甚至更快。不幸的是,它在任何版本的Internet explorer中都不起作用。表中的数字指定完全支持该方法的第一个浏览器版本:

最有效的方法是https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

下面是简短版本。

  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;
  };
  var a = "a";
  console.debug(a.repeat(10));

Mozilla的Polyfill:

if (!String.prototype.repeat) {
  String.prototype.repeat = function(count) {
    'use strict';
    if (this == null) {
      throw new TypeError('can\'t convert ' + this + ' to object');
    }
    var str = '' + this;
    count = +count;
    if (count != count) {
      count = 0;
    }
    if (count < 0) {
      throw new RangeError('repeat count must be non-negative');
    }
    if (count == Infinity) {
      throw new RangeError('repeat count must be less than infinity');
    }
    count = Math.floor(count);
    if (str.length == 0 || count == 0) {
      return '';
    }
    // Ensuring count is a 31-bit integer allows us to heavily optimize the
    // main part. But anyway, most current (August 2014) browsers can't handle
    // strings 1 << 28 chars or longer, so:
    if (str.length * count >= 1 << 28) {
      throw new RangeError('repeat count must not overflow maximum string size');
    }
    var rpt = '';
    for (;;) {
      if ((count & 1) == 1) {
        rpt += str;
      }
      count >>>= 1;
      if (count == 0) {
        break;
      }
      str += str;
    }
    // Could we try:
    // return Array(count + 1).join(this);
    return rpt;
  }
}

在一个新的ES6和声中,你将有自己的方法来重复。此外,ES6目前只是实验性的,该功能已在Edge、FF、Chrome和Safari中提供

"abc".repeat(3) // "abcabcabc"

当然,如果重复功能不可用,您可以使用旧的好数组(n+1).join(“abc”)

Array(10).fill('a').join('')

尽管投票最多的答案有点紧凑,但使用这种方法,您不必添加额外的数组项。