在 JavaScript 中重复一个字符串多次 [英] Repeat a string in JavaScript a number of times
问题描述
在 Perl 中,我可以使用以下语法多次重复一个字符:
$a = "a" x 10;//结果是aaaaaaaaaa"
是否有一种简单的方法可以在 Javascript 中完成此操作?我显然可以使用函数,但我想知道是否有任何内置方法或其他一些巧妙的技术.
最近,repeat
字符串方法几乎在任何地方实现.(不在 Internet Explorer 中.) 所以除非你需要支持旧浏览器,否则你可以简单地写:
"a".repeat(10)
在repeat
之前,我们使用了这个hack:
Array(11).join("a")//创建 10 个 a 的字符串: "aaaaaaaaaa";
(请注意,长度为 11 的数组只能得到 10 个a",因为 Array.join
将参数放在数组元素之间.)>
Simon 还指出,根据这个基准,它似乎在 Safari 和 Chrome 中更快(但不是Firefox) 通过简单地使用 for 循环追加来多次重复一个字符(虽然不那么简洁).
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 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.
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 benchmark, 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屋!