重复字符N次

编程入门 行业动态 更新时间:2024-10-24 15:19:35
本文介绍了重复字符N次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在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次

本文发布于:2023-11-30 20:17:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651356.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!