Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

javascript - 重复字符N次(Repeat Character N Times)

In Perl I can repeat a character multiple times using the syntax:(在Perl中,我可以使用以下语法多次重复一个字符:)

$a = "a" x 10; // results in "aaaaaaaaaa" Is there a simple way to accomplish this in Javascript?(有没有简单的方法可以在Javascript中完成此操作?) I can obviously use a function, but I was wondering if there was any built in approach, or some other clever technique.(我显然可以使用函数,但是我想知道是否有任何内置方法或其他一些巧妙的技术。)   ask by Steve translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

These days, the repeat string method is implemented almost everywhere.(如今, repeat字符串方法 几乎在所有地方都已实现。)

(It is not in Internet Explorer .) So unless you need to support older browsers, you can simply write:((它不在Internet Explorer中 。)因此,除非需要支持较旧的浏览器,否则只需编写以下内容:) "a".repeat(10) Before repeat , we used this hack:(在repeat之前,我们使用了这个技巧:) 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.)((请注意,长度为11的数组只会使您获得10个“ a”,因为Array.join将参数放在数组元素之间 。)) 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).(Simon还指出,根据此jsperf ,似乎在Safari和Chrome(但不是Firefox)中,通过简单地使用for循环附加(虽然不太简洁)多次重复字符是更快的。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...