重复字符N次 [英] Repeat Character N 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)
在重复
之前,我们使用了这个hack:
Before repeat
, we used this hack:
Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"
(注意,长度为11的数组只能获得10a,因为数组.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).
这篇关于重复字符N次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!