Repeat Character N Times

后端 未结 23 2544
栀梦
栀梦 2020-11-22 11:51

In Perl I can repeat a character multiple times using the syntax:

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

Is there a simple way to ac

23条回答
  •  情话喂你
    2020-11-22 12:16

    These days, the repeat string method is implemented almost everywhere. (It is not in Internet Explorer.) So unless you need to support older browsers, you can simply write:

    "a".repeat(10)
    

    Before repeat, we used this hack:

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

    (Note that an array of length 11 gets you only 10 "a"s, since Array.join puts the argument between the array elements.)

    Simon also points out that according to this jsperf, it appears that it's faster in Safari and Chrome (but not Firefox) to repeat a character multiple times by simply appending using a for loop (although a bit less concise).

提交回复
热议问题