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

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

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


当前回答

如今,重复字符串方法几乎在所有地方都得到了实现。(它不在Internet Explorer中。)因此,除非您需要支持较旧的浏览器,否则只需编写:

"a".repeat(10)

在重复之前,我们使用了这个黑客:

Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"

(注意,长度为11的数组只能得到10个“a”,因为array.join将参数放在数组元素之间。)

西蒙还指出,根据这个基准,在Safari和Chrome(而不是Firefox)中,通过简单地使用for循环追加一个字符来重复多次似乎更快(虽然有点不那么简洁)。

其他回答

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 stringRepeat = function(string, val) {
  var newString = [];
    for(var i = 0; i < val; i++) {
      newString.push(string);
  }
  return newString.join('');
}

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

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

例如:

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

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

/**  
 * 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