Joost said:
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";
}
Any better solutions?
var a = [];
for (var i = 0; i < 5; i++) {
a.push("x");
}
var str = a.join("");
which won't work on quite a few browsers,
- The Array literal requires JavaScript 1.3, JScript 2.0, ECMAScript 3.
- Array.prototype.push() requires JavaScript 1.2, JScript 5.5, ECMAScript 3.
- Array.prototype.join() requires JavaScript 1.1, JScript 2.0, ECMAScript 1.
So yes, it is not going to work in Netscape Navigator before version 4.06
and Internet Explorer before version 5.5. However, if that is desired,
maximum compatibility (to JavaScript 1.1, JScript 2.0, ECMAScript 1) can be
achieved with slight modifications:
var a = new Array();
for (var i = 0; i < 5; i++)
{
a[a.length] = "x";
}
var str = a.join("");
See
http://PointedEars.de/es-matrix
and may or may not be slower.
Efficiency can be increased with:
for (var i = 5; i--
{
// ...
}
Here are the (for me rather surprising) benchmark results (10 * 50'000
iterations) from Firefox 2.0.0.11 on Windows XP SP 2 on a Pentium M 740:
Approach | avg | min | max (all in ms)
-----------------------------------+-----+-----+----------------
+= | 444 | 328 | 1297
+=/i-- | 372 | 265 | 1187
[]/push()/join() | 639 | 453 | 1297
[]/push()/join()/i-- | 617 | 391 | 1250
new Array()/a[a.length]/join() | 681 | 485 | 1375
new Array()/a[a.length]/join()/i-- | 605 | 421 | 1297
So it would appear optimized concatenation beats them after all.
PointedEars