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

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

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


当前回答

在CoffeeScript中:

( 'a' for dot in [0..10]).join('')

其他回答

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

例如:

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

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

Lodash提供了与Javascript repeat()函数类似的功能,这在所有浏览器中都不可用。它名为_.repeat,从3.0.0版开始提供:

_.repeat('a', 10);

在CoffeeScript中:

( 'a' for dot in [0..10]).join('')

如果您不反对在项目中包含库,lodash有一个repeat函数。

_.repeat('*', 3);
// → '***

https://lodash.com/docs#repeat

var stringRepeat = function(string, val) {
  var newString = [];
    for(var i = 0; i < val; i++) {
      newString.push(string);
  }
  return newString.join('');
}

var repeatedString = stringRepeat("a", 1);