Re: Character Repeat
- From: Dr J R Stockton <jrs@xxxxxxxxxxxxxxxxxx>
- Date: Fri, 1 Feb 2008 13:55:28 +0000
In comp.lang.javascript message <abc29a16-e0f3-43ac-9db3-9b7573a19db0@s3
7g2000prg.googlegroups.com>, Thu, 31 Jan 2008 15:16:43, RobG
<rgqld@xxxxxxxxxxxx> posted:
On Feb 1, 7:57 am, "bla...@xxxxxxxxxxxx" <bla...@xxxxxxxxxxxx> wrote:
I'm looking for an easy way to repeat a character.
For example in Perl if you want 5 "x"'s the code is
$str = "x" x 5; # result xxxxx
I've tried a few ways in javascript to accomplish this, but can not
come up with anything other then the lame old basic way which is
probably more processing then required...
var str = "";
for (var i = 0; 5 > i; i++){
str += "x";
}
Essentially, that's it.
<Panto> Oh no it isn't ! </Panto>
It can be optimised though: the += compound
operator is notoriously slow in some browsers, an Array with push/join
is usually faster, it shouldn't be slower. A while or do..while loop
should be faster than a for loop, consider something like:
Google : +JavaScript +"Making a Long String" finds
<URL:http://www.merlyn.demon.co.uk/js-misc0.htm#MLS>.
That shows that EvertJan used to know a short, fast method; and I a
faster - that is especially so for big repeats.
function BigCat(L) {
if (!L) return ""
if (L&1) return BigCat(L-1) + "x"
var T = BigCat(L>>1) ; return T + T }
function EjHCat(L) { return new Array(L+1).join('*') }
It's a good idea to read the newsgroup c.l.j and its FAQ. See below.
--
(c) John Stockton, nr London UK. ?@merlyn.demon.co.uk IE6 IE7 FF2 Op9 Sf3
news:comp.lang.javascript FAQ <URL:http://www.jibbering.com/faq/index.html>.
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
.
- References:
- Re: Character Repeat
- From: RobG
- Re: Character Repeat
- Prev by Date: Re: Prevent logon form display if cookies disabled
- Next by Date: Re: Character Repeat
- Previous by thread: Re: Character Repeat
- Next by thread: Re: Character Repeat
- Index(es):
Relevant Pages
|