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

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

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


当前回答

另一种快速重复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;
};

其他回答

适用于所有浏览器

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

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中都不起作用。表中的数字指定完全支持该方法的第一个浏览器版本:

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

_.repeat('a', 10);

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

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

https://lodash.com/docs#repeat

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

例如:

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

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

为了好玩,这里有另一种方法,使用toFixed()来格式化浮点数。

通过做

(0).toFixed(2)
(0).toFixed(3)
(0).toFixed(4)

我们得到

0.00
0.000
0.0000

如果前两个字符为0。我们可以使用这个重复模式来生成任何重复。

函数重复(str,nTimes){return(0).toFixed(n次).substr(2).replaceAll(“0”,str);}console.info(重复('3',5));console.info(重复('hello',4));