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

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

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


当前回答

以下是我使用的:

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

其他回答

在CoffeeScript中:

( 'a' for dot in [0..10]).join('')
/**  
 * 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"
);

截至目前,96.39%的浏览器支持String.repeat()。

function pad(text, maxLength){ 
  return text + "0".repeat(maxLength - text.length);
}
console.log(pad('text', 7)); //text000
String.prototype.repeat = function (n) { n = Math.abs(n) || 1; return Array(n + 1).join(this || ''); };

// console.log("0".repeat(3) , "0".repeat(-3))
// return: "000" "000"

适用于所有浏览器

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

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