重复字符N次

Ste*_*eve 573 javascript string character repeat

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

$a = "a" x 10; // results in "aaaaaaaaaa"
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法来实现这个Javascript?我显然可以使用一个函数,但我想知道是否有任何内置方法,或其他一些聪明的技术.

Jas*_*rff 1147

这些天来,该repeat字符串的方法来实现,几乎无处不在.(它不在Internet Explorer中.)因此,除非您需要支持旧版浏览器,否则您只需编写:

"a".repeat(10)
Run Code Online (Sandbox Code Playgroud)

之前repeat,我们使用过这个hack:

Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"
Run Code Online (Sandbox Code Playgroud)

(注意,长度为11的数组只能使用10"a",因为Array.join将参数放在数组元素之间.)

西蒙还指出,根据这个jsperf,似乎在Safari和Chrome(但不是Firefox)中通过简单地使用for循环附加多次重复一个字符会更快(虽然不那么简洁).

  • 循环方法可能更快但更冗长.另外,我对第一条评论的所有评价感到困惑,考虑到当数组长度可变时通常会有用,例如`Array(rawValue.length + 1).join("*")` (7认同)
  • 另外,您可以使用变量而不是固定长度 - 数组(20-len),比如填充最多20个字符串. (4认同)
  • @Neel那是因为JS引擎对字符串长度施加了限制。在 Chrome 和 Firefox 中,该限制接近 2^30(大约十亿)。10^12 是一万亿。 (3认同)
  • 公式是`Array(n + 1).join("a")`.当n = 0时,返回空字符串,当n = 1时,返回""a"`.所以我认为它适用于所有情况. (2认同)

Sal*_*ali 294

在一个新的ES6和声中,你将有自然的方式来重复这样做.此外ES6现在只是实验性的,此功能在Edge,FF,Chrome和Safari中提供

"abc".repeat(3) // "abcabcabc"
Run Code Online (Sandbox Code Playgroud)

当然,如果没有重复功能,你可以使用旧货 Array(n + 1).join("abc")


ken*_*bec 54

如果你重复自己很方便:

String.prototype.repeat = String.prototype.repeat || function(n){
  n= n || 1;
  return Array(n+1).join(this);
}

alert(  'Are we there yet?\nNo.\n'.repeat(10)  )
Run Code Online (Sandbox Code Playgroud)

  • 污染内置的原型是一种糟糕的编码实践. (53认同)
  • 我将删除`n = n || 1`部分(或检查`n`是否未定义),所以你也可以重复'0`次. (4认同)
  • @nurettin看到http://programmers.stackexchange.com/questions/104320/why-is-extending-the-dom-built-in-object-prototypes-a-bad-idea更多的讨论.我将添加一个(正确范围的)静态辅助函数,其签名为"repeat(str,n)". (3认同)
  • 另请参阅Mozilla的ES6官方polyfill:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat (3认同)
  • @ChrisV,`String.repeat`仅在ES6中添加,直到2015年6月才最终确定.所以我认为我的观点在2012年我写的时候是有效的.:) (3认同)

Kon*_*rov 13

性能最佳的方式是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));
Run Code Online (Sandbox Code Playgroud)

来自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;
  }
}
Run Code Online (Sandbox Code Playgroud)


bon*_*bon 12

另一种选择是:

for(var word = ''; word.length < 10; word += 'a'){}
Run Code Online (Sandbox Code Playgroud)

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

for(var word = ''; word.length < 10 * 3; word += 'foo'){}
Run Code Online (Sandbox Code Playgroud)

注意:您不必像1一样超调1word = Array(11).join('a')


小智 10

如果您不反对在项目中包含库,则lodash具有重复功能.

_.repeat('*', 3);
// ? '***
Run Code Online (Sandbox Code Playgroud)

https://lodash.com/docs#repeat


Joh*_*ers 10

适用于所有浏览器

以下函数的执行速度比接受的答案中建议的选项快得多:

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

你会这样使用它:

var repeatedString = repeat("a", 10);
Run Code Online (Sandbox Code Playgroud)

要比较此函数的性能与接受的答案中提出的选项的性能,请参阅此小提琴此小提琴的基准.

仅适用于现代浏览器

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

var repeatedString = "a".repeat(10);
Run Code Online (Sandbox Code Playgroud)

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

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

在此输入图像描述


Grz*_*lik 8

Array(10).fill('a').join('')
Run Code Online (Sandbox Code Playgroud)

虽然投票最多的答案更紧凑,但通过这种方法,您不必添加额外的数组项.

  • 如果您想要一个分隔符,这个答案很有用 (3认同)

Vic*_*ard 8

String.repeat()目前已有96.39%的浏览器支持。

function pad(text, maxLength){ 
  return text + "0".repeat(maxLength - text.length);
}
console.log(pad('text', 7)); //text000
Run Code Online (Sandbox Code Playgroud)


yck*_*art 7

/**  
 * Repeat a string `n`-times (recursive)
 * @param {String} s - The string you want to repeat.
 * @param {Number} n - The times to repeat the string.
 * @param {String} d - A delimiter between each string.
 */

var repeat = function (s, n, d) {
    return --n ? s + (d || "") + repeat(s, n, d) : "" + s;
};

var foo = "foo";
console.log(
    "%s\n%s\n%s\n%s",

    repeat(foo),        // "foo"
    repeat(foo, 2),     // "foofoo"
    repeat(foo, "2"),   // "foofoo"
    repeat(foo, 2, "-") // "foo-foo"
);
Run Code Online (Sandbox Code Playgroud)


web*_*deb 7

在ES2015/ES6中,您可以使用 "*".repeat(n)

所以只需将它添加到您的项目中,您就可以了.

  String.prototype.repeat = String.prototype.repeat || 
    function(n) {
      if (n < 0) throw new RangeError("invalid count value");
      if (n == 0) return "";
      return new Array(n + 1).join(this.toString()) 
    };
Run Code Online (Sandbox Code Playgroud)


csh*_*olk 5

另一种快速重复n个字符的有趣方法是使用快速取幂算法的思路:

var repeatString = function(string, n) {
    var result = '', i;

    for (i = 1; i <= n; i *= 2) {
        if ((n & i) === i) {
            result += string;
        }
        string = string + string;
    }

    return result;
};
Run Code Online (Sandbox Code Playgroud)


Jos*_*tos 5

只是为了好玩,这是使用toFixed() 的另一种方法,用于格式化浮点数。

通过做

(0).toFixed(2)
(0).toFixed(3)
(0).toFixed(4)
Run Code Online (Sandbox Code Playgroud)

我们得到

0.00
0.000
0.0000
Run Code Online (Sandbox Code Playgroud)

0.如果删除前两个字符,我们可以使用此重复模式来生成任何重复。

(0).toFixed(2)
(0).toFixed(3)
(0).toFixed(4)
Run Code Online (Sandbox Code Playgroud)