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

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

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


当前回答

最有效的方法是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;
  }
}

其他回答

也可用作一个衬垫:

function repeat(str, len) {
    while (str.length < len) str += str.substr(0, len-str.length);
    return str;
}

对于重复项目中的值,我使用repeat

例如:

var n = 6;
for (i = 0; i < n; i++) {
    console.log("#".repeat(i+1))
}

但要小心,因为该方法已添加到ECMAScript 6规范中。

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

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

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

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

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

另一种选择是:

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

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

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

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