在JavaScript中多次重复一个字符串 [英] Repeat a string in JavaScript a number of times
问题描述
在Perl中,我可以使用以下语法多次重复一个字符:
In Perl I can repeat a character multiple times using the syntax:
$a = "a" x 10; // results in "aaaaaaaaaa"
有没有一种简单的方法可以用Javascript完成此操作?我显然可以使用一个函数,但是我想知道是否有任何内置方法或其他一些巧妙的技术.
Is there a simple way to accomplish this in Javascript? I can obviously use a function, but I was wondering if there was any built in approach, or some other clever technique.
推荐答案
这些天来,不在Internet Explorer中.)因此,除非您需要支持较旧的浏览器,否则只需编写以下内容即可:
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)
在repeat
之前,我们使用了此技巧:
Before repeat
, we used this hack:
Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"
(请注意,长度为11的数组只会给您10个"a",因为Array.join
将参数放在数组元素之间.)
(Note that an array of length 11 gets you only 10 "a"s, since Array.join
puts the argument between the array elements.)
Simon还指出,根据此jsperf ,它在Safari和Chrome中似乎更快(但不是Firefox),只需使用for循环附加附加字符即可多次重复一个字符(尽管不太简洁).
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).
这篇关于在JavaScript中多次重复一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!